sql消息表查询

时间:2012-12-16 20:03:12

标签: mysql sql oracle

这是我的对话表:

conversationID  ||  userID
      1         ||    1
      1         ||    2
      2         ||    1
      2         ||    2
      2         ||    3

您可以看到每个会话可以包含2个或更多用户。

我试图获得只有2个用户在那里的对话的ID。 即仅包含用户1和1的会话。 2,答案是对话1。

但我怎么得到它?

3 个答案:

答案 0 :(得分:2)

你应该使用having子句。假设(conversationID,userID)是PK或AK,您的查询是:

  select   conversationID
    from   your_Table
group by   conversationID
  having   count( * ) = 2

已编辑加入了1,2个用户对话,这是一种索引友好的方法,没有相关的子查询,也没有逐行的功能。

      select   t1 conversationID
        from   your_Table t1
  inner join 
               ( select distinct conversationID
                  from your_Table
                 where userId in (1, 2)
               ) t2
          on   t1.conversationID = t2.conversationID
    group by   t1.conversationID
      having   count( distinct t1.userId ) = 2

答案 1 :(得分:2)

这将选择所有具有用户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

答案 2 :(得分:2)

希望这会对你有所帮助,

select conversationID from conversation
group by ConversationID having count(distinct UserID)=2;

sqlfiddle demo