如何重构此MySQL查询(2个表)?

时间:2019-03-18 18:31:56

标签: mysql

我有这两个表:

TABLE: xg_posts

TABLE: xg_postmeta

然后,我这样做:

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

非常感谢您!

1 个答案:

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