我希望能够查询MySQL数据库,以便根据父母和孩子找到一个人的兄弟姐妹。我们假设在这里假设一个人的父母的孩子,以及一个人的孩子的父母是该人的兄弟姐妹。
人
id name
-----------
1 jonny
2 tom
3 sally
4 bill
5 katie
6 jessica
RELS
id parent child
--------------------
1 2 3
2 5 6
3 2 1
4 1 6
5 1 4
6 6 2
我一直在试图弄清楚如何以一种给我这些结果的方式加入这两个表,但我无法做到。
SELECT people.id,people.name FROM people, rels
INNER JOIN rels children ON people.id = rels.parent
INNER JOIN rels siblings ON children.id = siblings.child
WHERE children.child = '1'
答案 0 :(得分:0)
试试这个
SELECT people.id,people.name FROM people
LEFT JOIN rels children ON people.id = children.parent
LEFT JOIN rels siblings ON people.id = siblings.child
WHERE children.child = '1'
group by people.id
答案 1 :(得分:0)
我已经提出了一个使用UNIONs的解决方案,我认为现在这样做。如果有人能想出一个纯粹基于JOIN的解决方案,我很乐意看到它!
SELECT people.*,c.* FROM rels
INNER JOIN rels c ON rels.parent = c.parent
INNER JOIN people ON people.id = c.child
WHERE rels.child = '1' AND people.id <> '1'
UNION
SELECT people.*,p.* FROM rels
INNER JOIN rels p ON rels.child = p.child
INNER JOIN people ON people.id = p.parent
WHERE rels.parent = '1' AND people.id <> '1'
答案 2 :(得分:0)
我没有对此进行测试,但这应该可行:
SELECT ppl.* from people as ppl
INNER JOIN rels AS par1 on ppl.id = par1.child
INNER JOIN rels as par2 on par2.parent = par1.parent
INNER JOIN people as sib on sib.id = par2.child
WHERE ppl.id = '3'
以sally(id = 3)
为例进行说明从PPL中选择要找到兄弟姐妹的人。 (id = 3)
从PAR1(父级)中选择其父级。选择父= 2
从PAR2(父)选择相同的父选择父= 2
从SIB(人员)中选择id = 3,1
的详细信息如果这不起作用,请告诉我......