2013-06-23 58 views
-3

我有一個數據庫,其中包含usersconversationsconversation_user檢查兩個用戶是否屬於同一個對話

現在我想知道兩個用戶是否正在進行對話。我怎樣才能以聰明的方式做到這一點?

在這種情況下,user1user2正在進行對話。

enter image description here

+2

你目前有什麼代碼? –

+1

如果pair('conversation_id,user_id)'應該是唯一的,那麼'id'列是什麼? –

+0

對落後者 - 這怎麼不是一個真正的問題? –

回答

2

這將列出所有conversation_id用戶1和用戶2的共同點:

SELECT conversation_id 
FROM  conversations 
WHERE user_id IN (1, 2) 
GROUP BY conversation_id 
HAVING COUNT(DISTINCT user_id)=2 

請參閱小提琴here

+0

這只是完美的工作! –

+0

謝謝!這也幫助了我! :d –

0
select count('x') 
from 
    conversation_user x 
where 
    (x.userid1 = 1 and x.userid2 = 2) or 
    (x.userid1 = 2 and x.userid2 = 1) 

如果該查詢返回0,那麼他們是不是有一個對話。否則他們是。

0

自加入可以做到這一點:

SELECT c.conversation_id 
FROM conversations c 
JOIN conversations c2 
    ON c.conversation_id=c2.conversation_id 
WHERE c.user_id=<x> AND c2.user_id=<y> 
相關問題