回答

收藏

sql消息表查询

技术问答 技术问答 292 人阅读 | 0 人回复 | 2023-09-12

这是我的对话表:0 |# O  ^) H! b$ a
conversationID  ||  userID                                                                                                                                                                                      ||    1                                                                                                                                                                                      ||    2    2   2                                                                                                                                                                                                                               2                                                                                                                                                                                                                                                                            ||     1     2                               ||    2    2   2                                                                                                                                                                                                                               2                                                                                                                                                                                                                                                                            ||    3如你所见,每个会话可以包含两个或两个以上的用户。* _4 a5 W0 y) p
我试图获得只有两个用户的对话ID。也就是说,只有用户1和2的对话,答案是对话1。: n9 @/ f9 I5 Z7 F
但是我怎么得到呢?
& }' l& `" J/ J& A! C8 J                                                                . L" m& V; X, `7 k5 a# E
    解决方案:                                                               
( N0 G( B" s" Z0 j                                                                这将选择所有用户1或用户2或同时有两个用户但没有其他用户的对话:. A- R  O% c4 y* \. \
select conversationIDfrom conversationsgroup by conversationIDhaving count(*) = count(case when userID in (1,2) then 1 end)如果您还希望所有会话都具有完全相同的用户1和2,而没有其他用户,则还必须添加和条件:
- b! M  |; p. x4 y( @2 Fselect conversationIDfrom conversationsgroup by conversationIDhaving count(*) = count(case when userID in (1,2) then 1 end)       and count(*) = 2 -- number of elements in set若可复制userID,则最好使用distinct:: A% y9 Q) C# G5 H# O9 i5 N
select conversationIDfrom conversationsgroup by conversationIDhaving  count(distinct userID) = count(distinct case when userID in (1,2) then userID end)  and count(distinct userID) = 2 -- number of elements in set
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则