2014-02-07 3 views
0

테이블, 스레드가 있습니다. thread_participants 테이블이 있습니다. 특정 thread_id 및 특정 thread_participants.user_id를 식별하는 행을 분리하려고합니다.SQL 쿼리에서 행을 분리하십시오.

예를 들어 thread_id = 5가 thread_participants.user_id = 6과 일치하고 다른 thread_participants와 일치하면 thread_id를 알고 싶습니다.

SELECT tp.thread_id FROM thread_participants tp WHERE tp.user_id = $user_id AND tp.user_id != ANYBODY ELSE 

답변

0
:

그러나, 예를 들어, thread_participants.user_id = 6 AND thread_participants.user_id = 9 = 7 경기를 thread_id 경우, 나는 그 같은

뭔가를 thread_id 알고 싶지 않아

당신은 집계와 함께이 작업을 수행 할 수 있으며, having 절 :

SELECT tp.thread_id 
FROM thread_participants tp 
GROUP BY tp.thread_id 
HAVING sum(tp.user_id = $user_id) > 0 and 
     sum(tp.user_id <> $user_id) = 0; 

이 첫 번째 조건은 각 스레드 그쪽의 테이블의 행 수를 계산 사용자와 일치하지 않습니다. > 0은 최소한 하나 이상 있는지 확인합니다.

두 번째 조건은 사용자와 일치하지 않는 각 스레드의 행 수를 계산합니다. = 0은 아무 것도 없도록합니다.

having 절을 사용하면 매우 유연하고 많은 조건에 적응할 수 있습니다.

+0

Wonderful, 내가 변경 한 것은 (tp.user_id <$ user_id) to (tp.user_id! = $ user_id)뿐이었습니다. 다른 방법으로 오류가 발생했습니다. – compguy24

관련 문제