选择连接表的列值作为结果列名称

时间:2012-11-06 11:09:23

标签: mysql sql wordpress join pivot

我有一个包含以下表格的WordPress数据库

帖子

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

postmeta

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

并拥有meta_keylatitudelongitude

的记录

如何编写SQL以显示latitudelongitude作为结果列名称?

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

以下查询是我的出发点

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 个答案:

答案 0 :(得分:3)

听起来您想要PIVOT latitudelongitudePIVOT。不幸的是,MySQL没有CASE函数,但您可以使用带有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 语句的聚合函数来复制它:

{{1}}

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

您可以使用以下内容:

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