如何在单列中返回两个表的SQL JOIN?
例如,对于给定的组ID,如何获取属于该组的所有人员及其所有朋友的单个列表?
基
-id
-name
groups_have_people
-groups_id
-people_id
人
-id
-name
-group_id
people_have_friends
-people_id1 (references people.id)
-people_id2 (references people.id)
例如,groups_have_people
包括{123}的people_id
1,2和3,而people_have_friends
包括记录1-2
,1-3
,{{1 }},1-4
,2-1
,我应该得到以下结果:
2-5
我可以执行以下操作,但它不会返回单个列表。
id Name
1 Mary
2 John
3 Burt
4 Jill
5 Sue
编辑看起来我可能不会使用JOIN来执行此操作,并且应该执行以下操作?
SELECT p1.*, p2.*
FROM people p1
INNER groups_have_people ghp ON ghp.people_id=p1.id
LEFT OUTER JOIN people_have_friends phf ON p1.id=phf.people_id1
LEFT OUTER JOIN people p2 ON p2.id=phf.people_id2
WHERE ghp.groups_id=123;
编辑2.添加更多样本数据
组
SELECT p.*
FROM people p
INNER groups_have_people ghp ON ghp.people_id=p.id
WHERE ghp.groups_id=123
UNION
SELECT people p1
INNER JOIN people_have_friends phf ON p1.id=phf.people_id1
INNER JOIN people p2 ON p2.id=phf.people_id2
WHERE p2.groups_id=123;
人
id name
111 Green
123 Blue
222 Yello
groups_have_people
id Name
1 Mary
2 John
3 Burt
4 Jill
5 Sue
6 Bob
7 Wilma
people_have_friends
groups_id people_id
111 1
111 5
123 1
123 2
123 3
222 3
222 7
编辑3.以下内容如何?
people_id1 people_id2
1 2
1 3
1 4
2 1
2 5
4 5
5 6
或
SELECT DISTINCT id,
name
FROM people
WHERE id IN
( SELECT people_id
FROM groups_have_people
WHERE groups_id=123
UNION SELECT phf.people_id
FROM people_have_friends phf
INNER JOIN groups_have_people ghp ON ghp.people_id=phf.people_id
WHERE ghp.groups_id=123);
答案 0 :(得分:0)
http://sqlfiddle.com/#!9/89a12/3
SELECT
p.id,
p.name
FROM groups_have_people ghp
INNER JOIN people p
ON ghp.people_id=p.id
WHERE ghp.groups_id=123
UNION
SELECT
p.id,
p.name
FROM groups_have_people ghp
INNER JOIN people p_temp
ON ghp.people_id=p_temp.id
INNER JOIN people_have_friends phf
ON p_temp.id=phf.people_id1
INNER JOIN people p
ON phf.people_id2=p.id
WHERE ghp.groups_id=123