2016-07-19 3 views
0

에 많은에서 SQL I 다음 스키마했습니다 :많은 관계

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' 행에 대한 사용자 ID가 둘 다 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 명인 경우에 매우 명확합니다.