2013-05-10 151 views
1

我正在開發消息系統。生成查詢

基本上我有2個表,會話表只保留id和關係表保持會話中的對話id和用戶id。

我的關係表;

|----------------|--------| 
| CONVERSATIONID | USERID | 
|----------------|--------| 
|  1  | 1 | 
|  1  | 2 | 
|  2  | 2 | 
|  2  | 3 | 
|  3  | 1 | 
|  3  | 2 | 
|  3  | 3 | 
|  3  | 4 | 
|  4  | 3 | 
|  4  | 1 | 
|  4  | 2 | 
|----------------|--------| 

當用戶想要發送新郵件,我檢查是否有用戶之間的對話。例如,用戶(id 1)選擇用戶標識2發送消息,但他們已經擁有該對話並需要向該對話添加消息。

所以,我的問題是我無法在一個查詢中獲得存在的對話ID。

我可以通過此查詢獲取屬於用戶的對話ID;

SELECT DISTINCT CONVERSATIONID FROM RELATIONS 
WHERE CONVERSATIONID IN 
(
    SELECT DISTINCT CONVERSATIONID FROM RELATIONS WHERE USERID IN (1,2) 
) 

result : 1,2,3,4 

如果我運行這個查詢;

SELECT DISTINCT CONVERSATIONID FROM RELATIONS 
WHERE CONVERSATIONID IN 
(
    SELECT DISTINCT CONVERSATIONID FROM RELATIONS WHERE USERID IN (1,2) 
) 
AND USERID NOT IN (1,2) 

result : 2,3,4 

但我需要「id:1」這是這些用戶的對話。

我怎樣才能得到這個ID與一個查詢?

感謝

回答

3

這個問題被稱爲Relational Division

假設UserID是每個CONVERSATIONID獨特,

SELECT CONVERSATIONID 
FROM conversationTable a 
WHERE UserID IN (1, 2) AND -- <<== list of UserID you want to find 
     EXISTS 
     (
      SELECT 1 
      FROM conversationTable b 
      WHERE a.CONVERSATIONID = b.CONVERSATIONID 
      GROUP BY CONVERSATIONID 
      HAVING COUNT(*) = 2 -- <<== number of userID on the list 
     ) 
GROUP BY CONVERSATIONID 
HAVING COUNT(*) = 2 -- <<== number of userID on the list 
+0

這就是我一直在尋找的。感謝您的答覆和解釋鏈接。 – rcpayan 2013-05-10 10:33:40