복잡한 쿼리와 내 조언은 항상 간단하게 시작하는 것입니다 : 충분히 간단한
# Find friends A and B
select A.email as A_email, A.name as A_name, B.email as B_email, B.name as B_name
from user A
join friends
on A.email = friends.friend1_email
join user B
on B.email = friends.friend2.email
,의는 B와 C 다시 그것을 할 수 있습니다 :
# Find friends B and C
select B.email as B_email, B.name as B_name, C.email as C_email, C.name as C_name
from user B
join friends
on B.email = friends.friend1_email
join user C
on C.email = friends.friend2.email
이제 단일 쿼리에서 A, B 및 C를 결합하여
# Find friends A, B, and C
select A.email as A_email, A.name as A_name, B.email as B_email, B.name as B_name, C.email as C_email, C.name as C_name
from user A
join friends f1
on A.email = f1.friend1_email
join user B
on f1.friend2_email = B.email
join friends f2
on B.email = f2.friend1_email
join user C
on f2.friend2_email = C.email
위의 쿼리는 사용자 C와 친구 인 사용자 B와 친구 인 모든 사용자 A를 제공하지만 결과 세트를 A와 C가 친구가 아닌 레코드로 제한하지 않습니다. 결과 집합을 얻으려면 쿼리를 약간 수정해야합니다.
# Find friends A, B, and C
select A.email as A_email, A.name as A_name, B.email as B_email, B.name as B_name, C.email as C_email, C.name as C_name
from user A
join friends f1
on A.email = f1.friend1_email
join user B
on f1.friend2_email = B.email
join friends f2
on B.email = f2.friend1_email
join user C
on f2.friend2_email = C.email
left join friends f3
on A.email = f3.friend1_email
and C.email = f3.friend2_email
where
f3.friend1_email is null
방향 그래프를 탐색하려합니까? 그렇다면 순전히 순수한 SQL로 처리하기가 어려울 것입니다. 프로세스가 종종 재귀 적으로 반복적이기 때문입니다. – tadman
@tadman : 10 년 이상 재귀 쿼리가 SQL 표준에 있었기 때문에 깊이 재귀는 SQL과 관련하여 문제가되지 않습니다. MySQL만이 아직 그것을 할 수 없다. –
@a_horse_with_no_name SQL * 표준이 이러한 일을 허용하지만 이것은 MySQL입니다. – tadman