这是我的对话表:
conversationID || userID 1 || 1 1 || 2 2 || 1 2 || 2 2 || 3
如您所见,每个会话可以包含2个或更多用户。
我正在尝试获取只有2个用户的对话的ID。即,仅包含用户1和2的对话,答案是对话1。
但是我怎么得到呢?
这将选择所有具有用户1或用户2或同时具有两个用户但没有其他用户的对话:
select conversationID from conversations group by conversationID having count(*) = count(case when userID in (1,2) then 1 end)
如果您还希望所有会话都具有完全相同的用户1和2,而没有其他用户,则还必须添加和条件:
select conversationID from conversations group by conversationID having count(*) = count(case when userID in (1,2) then 1 end) and count(*) = 2 -- number of elements in set
如果可以复制userID,则最好使用distinct:
select conversationID from conversations group by conversationID having count(distinct userID) = count(distinct case when userID in (1,2) then userID end) and count(distinct userID) = 2 -- number of elements in set