简体   繁体   中英

Alternative to GROUP CONCAT

I stumbled upon this issue and can't seem to get the hang of it. I have three tables:

MSG_V3_THREAD

在此处输入图片说明

MSG_V3_THREAD_USERS

在此处输入图片说明

MSG_V3_THREAD_PARTNERS

在此处输入图片说明

Now, what I need to do is to get this table in the end:

在此处输入图片说明

(NOTE: the above image is photoshopped)

I cannot seem to find a solution to this. I managed to do a group_concat which gives me the correct result but it is not in the format I need. I also have this query at the moment:

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

Which results into this:

在此处输入图片说明

It just puts all the ids in one column.

Could anyone please help me with this? It might be that the solution is pretty simple but I just can't see it.

Thank you!

You had the right idea, you just need to switch around the explicit null s you're querying. Aliases are ignored in all the queries except the first when you use the union operator:

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

I think you just want union like this:

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;

Note that the union removes duplicates both within tables and between them. You could also write this as:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM