我有以下架构:
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
任何想法?
最佳答案
嗯这是使用group by
和having
的方法:
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