I have a table called participants with the following fields:
- id
- user_id
- conversation_id
The background is that there are conversations with at least two or more participants. I want to find a conversation that has only been held by two specified users, with no other users in the conversation.
I have come up with the following:
SELECT *
FROM participants
WHERE user_id = 1 OR user_id = 2
GROUP BY conversation_id
HAVING COUNT(*) = 1
Given this content
you can see that the users 1 and 2 share a conversation with user 3 (conversation 1), but also have one conversation alone (conversation 2).
The query above in fact returns the right conversation_id (i.e. 2) - but I am not sure whether the query is correct. When I say HAVING COUNT(*) = 2
it returns conversation 1, and I am not sure why. Intuitively I used having count - and it seems to work if set to 1 - but I am not sure what it does in this context.
Is the query correct? If so, why? If not, what do I need to change to make it work?
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
.
来源:https://stackoverflow.com/questions/13788433/mysql-find-conversation-only-being-held-by-two-users