我有一个像这样的表我正在尝试获取chat_id,其中成员是激动人心的匹配例如我想获得成员1,2的聊天ID但是当它像这样Select * member_to_chat WHERE member_id IN (1,2)
时它返回结果和从聊天号码3开始,这是错误的,因为在这个聊天中我有3个人需要,如果我给member_id 1和2只得到chat_id 1,是否可以用mysql做到这一点,提前谢谢!如果不好的话,对不起我的英语。
Member_to_chat
id | member_id | chat_id
1 1 1
2 2 1
----------------------
3 1 2
4 3 2
----------------------
5 1 3
6 2 3
7 3 3
给定member_id的结果1,2 - chat_id必须为1,或者如果我通过1,2,3必须返回chat_id 3,再次感谢您的任何建议
答案 0 :(得分:0)
select distinct chat_id
from member_to_chat m
where
not exists (select chat_id
from member_to_chat
where member_id not in(1,2)
and chat_id=m.chat_id)
and exists
(select chat_id
from member_to_chat
where member_id=1)
and exists
(select chat_id
from member_to_chat
where member_id=2)
答案 1 :(得分:0)
我喜欢使用group by
和having
来解决这些问题,因为这是一种非常灵活的方法来测试许多条件。如果你想要任何有1和2的聊天(但可能有3个):
select chat_id
from member_to_chat mtc
group by chat_id
having sum(member_id = 1) > 0 and
sum(member_id = 2) > 0;
只获得1和2 - 但没有其他人:
select chat_id
from member_to_chat mtc
group by chat_id
having sum(member_id = 1) > 0 and
sum(member_id = 2) > 0 and
sum(member_id in (1, 2)) = 0;