GROUP_CONCAT的替代方案

时间:2014-12-05 15:47:30

标签: mysql sql select

我偶然发现了这个问题,似乎无法解决这个问题。 我有三张桌子:

MSG_V3_THREAD

enter image description here

MSG_V3_THREAD_USERS

enter image description here

MSG_V3_THREAD_PARTNERS

enter image description here

现在,我需要做的是最终得到这个表:

enter image description here

(注意:上面的图片是photoshopped)

我似乎无法找到解决方案。我设法做了一个group_concat,它给了我正确的结果,但它不是我需要的格式。我现在也有这个问题:

SELECT  msg_v3_thread.thread_id, user_id, NULL as partner_id
FROM msg_v3_thread
LEFT JOIN msg_v3_thread_users ON msg_v3_thread_users.thread_id = msg_v3_thread.thread_id 
WHERE msg_v3_thread.thread_id = 3
UNION
SELECT  msg_v3_thread.thread_id, partner_id, NULL as user_id
FROM msg_v3_thread
LEFT JOIN msg_v3_thread_partners ON msg_v3_thread_partners.thread_id = msg_v3_thread.thread_id 
WHERE msg_v3_thread.thread_id = 3

结果如下:

enter image description here

它只是将所有ID放在一列中。

有人可以帮我这个吗?可能解决方案很简单,但我看不到它。

谢谢!

2 个答案:

答案 0 :(得分:1)

你有正确的想法,你只需要切换你正在查询的显式null。除了使用union运算符的第一个查询外,所有查询都会忽略别名:

SELECT  msg_v3_thread.thread_id, user_id, NULL as partner_id
FROM msg_v3_thread
LEFT JOIN msg_v3_thread_users ON msg_v3_thread_users.thread_id = msg_v3_thread.thread_id 
WHERE msg_v3_thread.thread_id = 3
UNION
SELECT  msg_v3_thread.thread_id, NULL as user_id, partner_id -- Here!
FROM msg_v3_thread
LEFT JOIN msg_v3_thread_partners ON msg_v3_thread_partners.thread_id = msg_v3_thread.thread_id 
WHERE msg_v3_thread.thread_id = 3

答案 1 :(得分:1)

我想你只想union这样:

select thread_id, user_id, NULL as partner_id
from MSG_V3_THREAD_USERS
where thread_id = 3
union
select thread_id, NULL, partner_id
from MSG_V3_THREAD_PARTNERS
where thread_id = 3;

请注意,union会删除表格内和表格之间的重复项。您也可以将其写为:

select distinct thread_id, user_id, NULL as partner_id
from MSG_V3_THREAD_USERS
where thread_id = 3
union all
select distinct thread_id, NULL, partner_id
from MSG_V3_THREAD_PARTNERS
where thread_id = 3;
相关问题