SQL选择多对多的关系

时间:2016-07-19 14:44:01

标签: mysql sql select join

我有以下架构:

Users
-----
id
name

Conversations
-------------
id
other

Partecipants (join table)
------------
id
user_id
conversation_id
other

用户可以进行多次对话,对话属于许多用户。

我需要选择具有其他用户子集的用户的所有会话。

我的尝试是(不工作):

SELECT     *
FROM       `conversations` 
INNER JOIN `participants` ON `conversations`.`id` = `participants`.`conversation_id` 
WHERE      `participants`.`user_id` = 1 
AND         (participants.user_id IN (4,6)) 
GROUP BY    participants.conversation_id 

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

嗯。以下是使用group byhaving的方法:

select p.conversation_id
from participants p
group by p.conversation_id
having sum(p.user_id = 1) > 0 and     -- user 1 in conversation
       sum(p.user_id in (4, 6)) > 0;   -- user 4 and/or 6 in conversation

答案 1 :(得分:1)

我从您的问题中了解到,您希望看到用户“4,6”参与与user_id = 1的对话。为此,请尝试按照查询进行操作。

 select * from (SELECT     conversations.id as conversation_id, participants.user_id as selectedUser,   GROUP_CONCAT(participants.user_id) AS participants
 FROM       `conversations` 
 INNER JOIN `participants` ON `conversations`.`id` = `participants`.`conversation_id` 
GROUP BY    participants.conversation_id ) as derivedTable 
where 
selectedUser=1 and 
(participants like '%4%' and participants like '%6%')

enter image description here

以上查询的作用是什么。最初它将从会话和参与者表中获取所有记录,并再次连接所有参与者user_id = 1。然后外部查询检查很清楚,找到user_id,参与者有4和6。