2016-02-28 67 views
0

我有以下表格。複雜的MySQL對話組查詢?

conversations 
| id | 
------ 
    1 

conversationMembers 
| id | conversationId | userId | email 
--------------------------------------- 
    1   1   2  null 
    2   1   null [email protected] 
    3   1   7  null 

基本上,我試圖構建一個MySQL查詢,通過conversationMembers的精確匹配返回從對話表中的一行。

因此,這裏有一些預期回報的例子。

假設我們想要一個會話id用於以下確切成員之間的會話:userId 2,userId 7,email [email protected] - 這會在conversationMembers表中看到具有相同對話ID的行以及完全匹配我們正在搜索的那個對話ID的所有成員。它將返回ID爲1的對話行。

這是另一個示例。我們希望在用戶標識2和用戶標識7之間進行對話的對話標識。這將看到用戶標識2和用戶標識7之間沒有對話,所以它不會返回任何內容。

最後一個例子。假設我們想要userId 7和userId 9,這也會看到這兩個用戶標識之間沒有獨佔對話,並且不會返回任何內容。

要做到這一點,最好的方法是什麼?我玩過子查詢,但是我所提出的一切似乎都無法處理完全匹配的情況 - 例如,我在選擇對話時遇到了問題 - 僅在userId 2和7上(它不會返回任何內容)並且正在接受對話1,儘管我沒有指定我想與[email protected]電子郵件進行對話。如果我搜索了所有會員的完全匹配的conversationId,我應該只會收到對話1返回。

回答

0

一種方法是使用group byhaving。這很好,因爲它可以表達什麼是靈活的。因此,您的第一個示例是:

select conversionid 
from conversationMembers 
group by conversionid 
having sum(userId = 2) > 0 and 
     sum(userId = 7) > 0 and 
     sum(email = '[email protected]') > 0; 

總計的條件計算匹配的成員數。 > 0表示至少有一個。對於第二種情況,該條款是:

having sum(userId = 2) > 0 and 
     sum(userId = 7) > 0 and 
     sum(userId not in (2, 7)) = 0; 

或者:

select conversionid 
from conversationMembers 
group by conversionid 
having sum(userId = 2) > 0 and 
     sum(userId = 7) > 0 and 
     count(distinct userId) = 2; 
+0

似乎完美地工作!謝謝! –