从多行中提取仅匹配一组值的特定记录

时间:2011-12-30 18:04:47

标签: sql

我正在尝试查找只有一组确切收件人的所有会话。我的表看起来像这样:

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],但我不想要任何其他记录,我将如何做到这一点。

4 个答案:

答案 0 :(得分:2)

您可以对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

答案 1 :(得分:0)

如果我理解正确:

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

答案 2 :(得分:0)

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>

其中&lt;用户ID&gt;是以逗号分隔的用户ID和&lt;用户数&gt;是这些用户的确切数量,例如在你的例子中有2个。

答案 3 :(得分:0)

首先找到对话框,其中user_id不在您的列表中(内部子查询),然后找到不在此列表中的conversation_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)))