Mysql - find conversation only being held by two users

前端 未结 2 1194
名媛妹妹
名媛妹妹 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: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.

提交回复
热议问题