连接2个结果集以替换列中的值

时间:2014-04-11 03:43:06

标签: mysql sql wordpress join

我有2个SQL结果数据集,我需要合并到一个看起来像:

Final Merged Table
-------------
320 Sydney
321 Brisbane
322 Melbourne

实现这一目标的SQL有点复杂,因为每个数据列都作为单独的记录保存在数据库中(由于Wordpress及其存储'meta_value'数据的方式)

第一个结果集:

User Table (A)
-------------
320 119 
321 120 
322 121 

达成:

SELECT wp_frm_items.id, meta_value AS city  FROM `wp_frm_items` 

INNER JOIN `wp_frm_item_metas` on wp_frm_item_metas.item_id = wp_frm_items.id 

WHERE `form_id` = 9 AND  field_id = 219

第二个结果集:

Location Table (B)
-------------
119 Sydney
120 Brisbane
121 Melbourne

达成:

SELECT wp_frm_items.id, meta_value FROM `wp_frm_items` 

INNER JOIN `wp_frm_item_metas` on wp_frm_item_metas.item_id = wp_frm_items.id 

WHERE `form_id` = 10

MySQL一直告诉我,我在第7行“INNER JOIN”的最终加入代码中出错: (以上2个SQL语句工作正常)

SELECT * 

FROM (SELECT wp_frm_items.id, meta_value AS city  FROM `wp_frm_items` 
INNER JOIN `wp_frm_item_metas` on wp_frm_item_metas.item_id = wp_frm_items.id 
WHERE `form_id` = 9 AND  field_id = 219 ) AS A 

INNER JOIN

SELECT * 

FROM (SELECT wp_frm_items.id, meta_value FROM `wp_frm_items` 
INNER JOIN `wp_frm_item_metas` on wp_frm_item_metas.item_id = wp_frm_items.id 
WHERE `form_id` = 10) AS B 

ON A.city = B.id

任何人都可以告诉我如何实现这一目标吗?

1 个答案:

答案 0 :(得分:1)

你非常接近。简短的回答是你不需要在join子句中使用SELECT * FROM,只需指定(派生)表本身:

SELECT * 

FROM (SELECT wp_frm_items.id, meta_value AS city  FROM `wp_frm_items` 
INNER JOIN `wp_frm_item_metas` on wp_frm_item_metas.item_id = wp_frm_items.id 
WHERE `form_id` = 9 AND  field_id = 219 ) AS A 

INNER JOIN
    (SELECT wp_frm_items.id, meta_value FROM `wp_frm_items` 
    INNER JOIN `wp_frm_item_metas` on wp_frm_item_metas.item_id = wp_frm_items.id 
    WHERE `form_id` = 10) AS B 

ON A.city = B.id