Selecting a join table's column values as resu

2019-07-13 17:01发布

I've a WordPress database with following tables

posts

+--------------+
| 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

2条回答
祖国的老花朵
2楼-- · 2019-07-13 17:24

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
查看更多
疯言疯语
3楼-- · 2019-07-13 17:41

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

查看更多
登录 后发表回答