Mysql - find conversation only being held by two users

前端 未结 2 1192
名媛妹妹
名媛妹妹 2021-01-14 20:21

I have a table called participants with the following fields:

  • id
  • user_id
  • conversation_id

The background is that there ar

相关标签:
2条回答
  • 2021-01-14 20:30
    select conversation_id
    from participants
    where user_id in (1,2)
    group by conversation_id
    having count(user_id) = 2
    

    Return two users conversation_id

    0 讨论(0)
  • 2021-01-14 20:39

    Using your query will not work since the where clause filters out the user_ids. Use

    SELECT * FROM participants
    GROUP BY conversation_id
    HAVING sum(user_id not in (1,2)) = 0
    

    user_id not in (1,2) returns 1 if a user_id other than 1,2 are in a conversation and 0 otherwise. So using SUM you can add up all that cases. If none are found then the sum is 0.

    0 讨论(0)
提交回复
热议问题