简体   繁体   中英

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! 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

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

I like to approach these problems using group by and having , because this is a very flexible way to test for many conditions. If you want any chat that has 1 and 2 (but could have 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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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