通过运行此选择查询:

SELECT wp_posts.ID, wp_postmeta.meta_key, wp_postmeta.meta_value
FROM wp_posts
INNER JOIN wp_postmeta
ON wp_posts.ID = wp_postmeta.post_id
WHERE wp_posts.post_status = 'publish'
AND wp_posts.post_type = 'my_post_type'
AND wp_posts.post_date < NOW()
AND wp_postmeta.meta_key = 'wpcf-lat'
OR wp_postmeta.meta_key = 'wpcf-long'

我有这样的桌子:
id     meta_key     meta_value
------------------------------
1270   wpcf-lat     12.6589
1270   wpcf-long    78.7425
1658   wpcf-lat     22.3654
1658   wpcf-long    65.2985

但我需要这样的结果表
id     wpcf-lat     wpcf-long
------------------------------
1270   12.6589      78.7425
1658   22.3654      65.2985

我怎样才能做到?

最佳答案

对于已知的meta_key集合,可以使用以下查询

select
wp.ID,
max(
   case when pm.meta_key = 'wpcf-lat' then pm.meta_value end
) as `meta_value`,
max(
  case when pm.meta_key = 'wpcf-long' then pm.meta_value end
) as `wpcf-long`
from wp_posts wp
join  wp_postmeta pm on pm.post_id = wp.ID
group by  wp.ID ;

关于mysql - SQL-如何串联此表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29121947/

10-11 05:06