Selecting a join table’s column values as result column name

I’ve a WordPress database with following tables

posts

Read More
+--------------+
| Field        |
+--------------+
| ID           |
| post_author  |
| post_title   | 
| post_type    | 
+--------------+

postmeta

+--------------+
| Field        |
+--------------+
| meta_id      |
| post_id      |
| meta_key     |
| meta_value   |
+--------------+

and have records with meta_key values latitude and longitude

How can I write SQL to show latitude and longitude as result column names?

+--------------+
| Field        |
+--------------+
| ID           |
| post_author  |
| post_title   |
| latitude     |
| longitude    | 
+--------------+

Below query is my starting point

SELECT ID, post_title, meta_key, meta_value FROM `wp_posts` 
LEFT JOIN `wp_postmeta` on ID=post_id 
WHERE post_type='place' AND (meta_key='latitude' OR meta_key='longitude') 
ORDER BY ID ASC

Related posts

Leave a Reply

2 comments

  1. It sounds like you want to PIVOT the latitude and longitude values. Unfortunately, MySQL does not have a PIVOT function but you can replicate it using an aggregate function with a CASE statement:

    SELECT p.ID, 
      p.post_title, 
      p.post_author,
      max(case when pm.meta_key='latitude' then pm.meta_value end) latitude,
      max(case when pm.meta_key='longitude' then pm.meta_value end) longitude
    FROM `wp_posts` p
    LEFT JOIN `wp_postmeta` pm
      on p.ID=pm.post_id 
    WHERE p.post_type='place' 
      AND (pm.meta_key='latitude' OR pm.meta_key='longitude') 
    GROUP BY p.ID, p.post_title, p.post_author
    ORDER BY p.ID ASC
    

    See SQL Fiddle with Demo

  2. You could use something like this:

    SELECT
      wp_posts.ID,
      wp_posts.post_title,
      wp_post_1.meta_value as latitude,
      wp_post_2.meta_value as longitude
    FROM
      wp_posts
      LEFT JOIN wp_postmeta wp_post_1
      ON wp_posts.ID=wp_post_1.post_id and wp_post_1.meta_key = 'latitude'
      LEFT JOIN wp_postmeta wp_post_2
      ON wp_posts.ID=wp_post_2.post_id and wp_post_2.meta_key = 'longitude'
    WHERE post_type='place'
    ORDER BY ID ASC