2016-07-19 101 views
0

我有以下模式:SQL選擇多對多的關係

Users 
----- 
id 
name 

Conversations 
------------- 
id 
other 

Partecipants (join table) 
------------ 
id 
user_id 
conversation_id 
other 

的用戶可以有很多的對話和交談屬於多個用戶。

我需要選擇一個用戶與其他用戶子集的所有對話。

我嘗試的(不工作):

SELECT  * 
FROM  `conversations` 
INNER JOIN `participants` ON `conversations`.`id` = `participants`.`conversation_id` 
WHERE  `participants`.`user_id` = 1 
AND   (participants.user_id IN (4,6)) 
GROUP BY participants.conversation_id 

任何想法?

+0

一個'Participants'行的用戶標識如何等於1和4或6?這沒有任何意義 – Bridge

回答

3

嗯。下面是使用group byhaving的方法:

select p.conversation_id 
from participants p 
group by p.conversation_id 
having sum(p.user_id = 1) > 0 and  -- user 1 in conversation 
     sum(p.user_id in (4, 6)) > 0; -- user 4 and/or 6 in conversation 
1

我從你的問題理解是你想看到用戶「4,6」參與與USER_ID = 1的對話這樣做試試下面的查詢。

select * from (SELECT  conversations.id as conversation_id, participants.user_id as selectedUser, GROUP_CONCAT(participants.user_id) AS participants 
FROM  `conversations` 
INNER JOIN `participants` ON `conversations`.`id` = `participants`.`conversation_id` 
GROUP BY participants.conversation_id) as derivedTable 
where 
selectedUser=1 and 
(participants like '%4%' and participants like '%6%') 

enter image description here

什麼上面的查詢確實是。最初它將從對話和參與者表中獲取所有記錄,並將所有參與者再次設爲user_id = 1。那麼外部查詢檢查非常清楚,找到user_id並且參與者有4和6.