【问题标题】:pulling specific record(s) that match only a set of values across multiple rows拉取仅与多行中的一组值匹配的特定记录
【发布时间】:2011-12-31 03:06:38
【问题描述】:

我正在尝试查找只有一组确切收件人的所有对话。我的表格如下所示:

Conversation
---------------
id | some other fields

User
---------------
id | some other fields

Recipients
--------------
id | conversation_id | user_id | some other fields
1  | 1               | 1
2  | 1               | 2        
3  | 2               | 1
4  | 2               | 2                
5  | 2               | 3
6  | 3               | 1
7  | 3               | 3

使用上面的方法我想得到conversation_id 1,我唯一知道的是user_id的[1,2],但我不想要任何其他记录我将如何去做。

【问题讨论】:

    标签: sql


    【解决方案1】:

    您可以在conversation_id 上进行分组,然后使用having 过滤掉正确的对话。在下面的查询中,第一行要求 user_id 1 和 2 都存在。第二行要求它不包含任何其他user_id

    select  conversation_id
    from    recipients
    group by
            conversation_id
    having  count(distinct case when user_id in (1,2) then user_id end) = 2
            and count(case when user_id not in (1,2) then 1 end) = 0
    

    【讨论】:

    • 我刚刚注意到 - 这不应该是from recipients,而不是conversation吗?
    • Dennis 指出了我的答案有问题 - 纠正它实际上会将其变成这个答案,所以我删除了我的答案。
    【解决方案2】:

    如果我理解正确:

     SELECT id
     , conversation_id 
     , user_id
     , ... other columsn
     FROM Recipients 
     WHERE converstaion_id = 1
     AND user_id IN (1,2)
    

    【讨论】:

    • 我不知道conversation_id,但是从结果中期望的conversation_id 是1。
    【解决方案3】:
    select c.* from Conversation c 
      where (select count(distinct user_id) from Recipients 
         where conversation_id=c.id and user_id in (<USER-IDS>))=<NUMBER-OF-USERS>
    

    其中 是逗号分隔的用户 ID, 是这些用户的确切数量,例如2 在你的例子中。

    【讨论】:

    • 这将匹配用户 1,2 和 3 之间的对话。where 子句将过滤掉 Mr. 3,子查询将返回 2。
    • 这是返回对话 1 和 2
    【解决方案4】:

    首先找到具有不在您列表中的 user_id 的会话 ID(内部子查询)然后查找不在此列表中的会话 ID

    SELECT DISTINCT conversation_id
    FROM         dbo.Recipients
    WHERE     (conversation_id NOT IN
                              (SELECT     Recipients_1.conversation_id
                                FROM          dbo.Recipients AS Recipients_1 LEFT OUTER JOIN
                                                           (SELECT id AS user_id
                                                             FROM          User
                                                             WHERE      (id IN (1, 2))) AS tbl_user ON tbl_user.user_id = Recipients_1.user_id
                                WHERE      (tbl_user.user_id IS NULL)))
    

    【讨论】:

    • 这将排除其他人之间的对话,但并不要求先生 1 和先生 2 都在场。顺便说一句,对于user_id,无需加入user
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多