2011-12-30 57 views
2

我正在嘗試查找所有僅包含一組確切收件人的對話。我的表是這樣的:拉特定記錄只匹配多個行中的一組值

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],但我不希望任何其他記錄我將如何去這樣做。

回答

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 
+0

完美作品 謝謝!! – dennis1600 2011-12-30 18:47:40

+0

我剛剛注意到了 - 不應該是來自收件人而是會話嗎? – 2011-12-30 18:48:52

+0

在你的代碼中你必須知道1)列表2)然後編號列表 – MRM 2011-12-30 18:48:56

0

如果我正確理解:

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

我不知道conversation_id,但conversation_id對結果的期望是1. – dennis1600 2011-12-30 18:16:28

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> 

其中< USER-IDS>是逗號分隔的用戶ID和< NUMBER-OF-USERS>是那些用戶的確切數目,例如2在你的例子中。

+0

這將匹配用戶1,2和3之間的對話。'where'子句將過濾出3,子查詢將返回2 – Andomar 2011-12-30 18:34:05

+0

這是返回對話1和2 – dennis1600 2011-12-30 18:34:49

0

先找到至極conversation_id有無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))) 
+0

這會排除其他人之間的對話,但並不要求先生1和先生2都在場。順便說一句,沒有必要加入'用戶'的'user_id'。 – Andomar 2011-12-30 18:39:32

相關問題