找到“多对多”的一些价值观

时间:2016-05-06 16:22:50

标签: mysql ruby-on-rails-4

table users: id, first_name, ...
table dialog_members: user_id, dialog_id
table dialogs: id, ...
table messages: id, dialog_id, ...

我如何通过两个user_id找到Dialog?

实施例: 的对话框

1

dialog_members

user_id | dialog_id
1       | 1
2       | 1
1       | 2
3       | 2
...

我需要选择user_id = 1和user_id = 2的对话框。

结果:id = 1

的对话框

1 个答案:

答案 0 :(得分:0)

SELECT Dialog_ID 
FROM dialog_members 
WHERE user_ID in (1,2) 
GROUP BY dialog_ID 
HAVING count(Distinct user_ID) = 2 

将列表限制为仅限用户1,2。 按dialog_ID分组,确保返回的dialog_ID具有不同的用户数2,由于where cluase

,因此只能是IDS 1,2