How to run SQL Query for multiple meta keys as columns, and their values as rows?


Staff member
Inside phpMyAdmin, I am working with custom meta fields in WordPress.

Say I have custom meta for 3 fields- Address, Latitude, Longitude and wish to run an SQL query to display only these 3 columns with their values as rows below.

I can only figure out how to get one of the columns to show, and it’s data by running this:

SELECT DISTINCT wp_postmeta.meta_value AS address
FROM wp_postmeta, wp_posts
WHERE post_type = ‘dealers’
AND wp_postmeta.meta_key = ‘_dealer_address’

Could someone point me in a direction of how to run the query to include all 3 columns?

What I’m trying to do is mimic the setup of the table in this: <a href="" rel="nofollow"></a>

Because I have a custom post type (dealers) using your custom metabox for latitude and longitude.

Your SQL query tested just fine in phpMyAdmin and looked identical to my other manually-created test dealer table, but when I tried to replace the google maps example query in the PHP- it was a no-go.

Is it too complicated of a query you think?

This is the test query that works without using the wordpress custom post:

$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance &lt; '%s' ORDER BY distance LIMIT 0 , 20",