简体   繁体   English

MySQL查询,获取确切值

[英]Mysql query, get exact value

I have a table like this one I'm trying to get chat_id where members are excat match for example I want to get chat id for members 1,2 but when do it like this Select * member_to_chat WHERE member_id IN (1,2) it returns results and from chat number 3, which is wrong because in this chat I have 3 people I need if I give member_id 1 and 2 to get only chat_id 1, Is it possible to do this with mysql, Thank you in advance! 我有一个这样的表,我试图获取chat_id,例如成员要与之匹配,我想获得成员1,2的聊天ID,但是当这样做时, Select * member_to_chat WHERE member_id IN (1,2) ,返回结果,并从聊天号码3中返回,这是错误的,因为在此聊天中,如果我给member_id 1和2仅获得chat_id 1,我需要3个人,是否可以使用mysql做到这一点,谢谢! and sorry for my English if it's not to good. 如果英语不好,请为我的英语感到抱歉。

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

the result for given member_id 1,2 - chat_id has to be 1, or if i pass 1,2,3 has to return chat_id 3, thank you again for any suggesstions 给定member_id 1,2的结果-chat_id必须为1,或者如果我通过1,2,3必须返回chat_id 3,再次感谢您的建议

http://sqlfiddle.com/#!9/d7519/3 http://sqlfiddle.com/#!9/d7519/3

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)

SQLFIDDLE DEMO SQLFIDDLE演示

I like to approach these problems using group by and having , because this is a very flexible way to test for many conditions. 我喜欢使用group byhaving解决这些问题,因为这是测试许多条件的非常灵活的方法。 If you want any chat that has 1 and 2 (but could have 3): 如果您想要进行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;

To get only 1 and 2 -- but no others: 仅获得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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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