我需要将2列合并为1行。列之间的关键是post_id
。
这是我的表(postmeta):
post_id meta_key meta_value
36 cp_state California
37 cp_state Illinois
38 cp_state California
39 cp_state California
40 cp_state California
36 cp_city Los Angeles
37 cp_city Chicago
38 cp_city San Diego
39 cp_city San Diego
40 cp_city Los Angeles
以下是我试图输出的内容:
post_id state city
36 California Los Angeles
37 Illinois Chicago
38 California San Diego
39 California San Diego
40 California Los Angeles
这是我使用的SQL,但得到了大量的结果:
SELECT a.post_id AS pID, a.meta_value AS state, b.meta_value AS city
FROM $wpdb->prefix"."postmeta AS a
LEFT JOIN $wpdb->prefix"."postmeta AS b
ON b.post_id = a.post_id
WHERE a.meta_key = 'cp_state'
AND b.meta_key = 'cp_city'
在我使用的直播Wordpress表中,显然有数百个其他meta_key
,所以我需要它来过滤这两个meta_key
(cp_city
,cp_state
)
答案 0 :(得分:3)
您应该使用INNER JOIN而不是LEFT JOIN
SELECT a.post_id AS pID, a.meta_value AS state, b.meta_value AS city
FROM $wpdb->prefix"."postmeta AS a
INNER JOIN $wpdb->prefix"."postmeta AS b
ON b.post_id = a.post_id
WHERE a.meta_key = 'cp_state'
AND b.meta_key = 'cp_city'