我有这两个表:
然后,我这样做:
SELECT xg_posts.post_title,
xg_posts.post_content,
CASE WHEN xg_postmeta.meta_key="bgmp_address" THEN xg_postmeta.meta_value ELSE NULL END AS address,
CASE WHEN xg_postmeta.meta_key="bgmp_latitude" THEN xg_postmeta.meta_value ELSE NULL END AS latitude,
CASE WHEN xg_postmeta.meta_key="bgmp_longitude" THEN xg_postmeta.meta_value ELSE NULL END AS longitude
FROM xg_postmeta, xg_posts
WHERE xg_posts.post_type = "bgmp"
AND xg_postmeta.post_id = xg_posts.ID
AND (xg_postmeta.meta_key = "bgmp_address"
OR xg_postmeta.meta_key = "bgmp_latitude"
OR xg_postmeta.meta_key = "bgmp_longitude")
ORDER BY xg_posts.post_title ASC
得到这个: Result from mentioned query
但是,我需要的是1 ROW的所有数据。 例如。
post_title | post_content |地址|经度|纬度
A.C.A。圣洛伦索(Est。21145)| AVDA。 SAN MARTIN 2898,圣洛伦佐| -32.7161131 | -60.7314613
非常感谢您!
答案 0 :(得分:0)
您需要分组和汇总。请注意max( )
和group by
子句:
SELECT xg_posts.post_title,
xg_posts.post_content,
max(CASE WHEN xg_postmeta.meta_key="bgmp_address" THEN xg_postmeta.meta_value ELSE NULL END) AS address,
max(CASE WHEN xg_postmeta.meta_key="bgmp_latitude" THEN xg_postmeta.meta_value ELSE NULL END) AS latitude,
max(CASE WHEN xg_postmeta.meta_key="bgmp_longitude" THEN xg_postmeta.meta_value ELSE NULL END AS longitude
FROM xg_postmeta, xg_posts
WHERE xg_posts.post_type = "bgmp"
AND xg_postmeta.post_id = xg_posts.ID
AND (xg_postmeta.meta_key = "bgmp_address"
OR xg_postmeta.meta_key = "bgmp_latitude"
OR xg_postmeta.meta_key = "bgmp_longitude")
GROUP BY xg_posts.post_title,
xg_posts.post_content
ORDER BY xg_posts.post_title ASC
根据post_content
的含义,您可能还需要在其上应用max
并将其从group by
子句中删除:
SELECT xg_posts.post_title,
max(xg_posts.post_content) AS post_content,
max(CASE WHEN xg_postmeta.meta_key="bgmp_address" THEN xg_postmeta.meta_value ELSE NULL END) AS address,
max(CASE WHEN xg_postmeta.meta_key="bgmp_latitude" THEN xg_postmeta.meta_value ELSE NULL END) AS latitude,
max(CASE WHEN xg_postmeta.meta_key="bgmp_longitude" THEN xg_postmeta.meta_value ELSE NULL END AS longitude
FROM xg_postmeta, xg_posts
WHERE xg_posts.post_type = "bgmp"
AND xg_postmeta.post_id = xg_posts.ID
AND (xg_postmeta.meta_key = "bgmp_address"
OR xg_postmeta.meta_key = "bgmp_latitude"
OR xg_postmeta.meta_key = "bgmp_longitude")
GROUP BY xg_posts.post_title
ORDER BY xg_posts.post_title ASC