0

我希望能够查询 MySQL 数据库以仅根据父母和孩子查找一个人的兄弟姐妹。我们在这里假设一个人的父母的孩子,一个人的孩子的父母是那个人的兄弟姐妹。

人们

id  name
-----------
1   jonny
2   tom
3   sally
4   bill
5   katie
6   jessica

相关

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'
4

3 回答 3

0

我想出了一个使用 UNION 的解决方案,我认为现在可以这样做。如果有人能提出一个纯粹基于 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'

http://sqlfiddle.com/#!2/45ba3/103/0

于 2013-04-27T00:44:23.657 回答
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 被选中

From PAR2 (Parent) select same parent Parent = 2 被选中

从 SIB(人员)中选择 id = 3,1 的详细信息

如果这不起作用,请告诉我...

于 2013-08-17T20:11:52.497 回答
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

在这里演示

于 2013-04-26T23:29:04.747 回答