我正在使用 SQL 来存储有关家谱的信息。我希望能够输入出生在X世代的人的名字,并输出出生在Z世代的所有后代的名字,但只有当这些后代是 sibling (具有同一 parent )。我找到了类似的解决方案,但我发现这些解决方案不适用于分层结构(由于别名)。 Y 代中可能还存在 parent 和他们的 child ,因此层次结构深度无法可靠地确定名称。
+----+----------+-----------+------------+--------+
| ID | Name | Parent_ID | Generation | Gender |
+----+----------+-----------+------------+--------+
| 1 | John | NULL | X | Male |
| 2 | Jill | 1 | Y | Female |
| 3 | Andy | 2 | Z | Male |
| 4 | Ralph | 2 | Z | Male |
| 5 | Lisa | NULL | X | Female |
| 6 | Steve | 5 | Y | Male |
| 7 | Sean | 6 | Y | Male |
| 8 | Sarah | 6 | Y | Female |
| 9 | Emily | 7 | Z | Female |
| 10 | Matt | 7 | Z | Male |
+----+----------+-----------+------------+--------+
所需输出:(if SET @GenX = 'Lisa';
)
+-------+
| Name |
+-------+
| Emily |
| Matt |
+-------+
这是我到目前为止的代码。
SET @GenX = 'Lisa';
SELECT t2.name AS Kids
FROM (SELECT name, Parent_ID
FROM FamilyTree
WHERE Gender = 'Male' OR Gender = 'Female') t1
LEFT JOIN FamilyTree t2 ON t2.ID = t1.Parent_ID
LEFT JOIN FamilyTree t3 ON t3.ID = t2.Parent_ID
LEFT JOIN FamilyTree t4 ON t4.ID = t3.Parent_ID
WHERE t3.name = '@GenX' OR t4.name - '@GenX'
GROUP BY t2.name
HAVING SUM(t1.Gender) > 0 AND SUM(t1.Gender) > 0;
这会返回正确的 parent 姓名,但不会返回 child 的姓名。如果我SELECT
和GROUP BY
child 的名字,我无法找到哪些 child 有姐妹/兄弟。谢谢您的帮助。我真的被这个问题困住了。
您可以假设没有重复的名字或重叠的家谱。
最佳答案
;with cte
as
(
Select id,name,Parent_id,generation,gender from family_tree where name =@name and generation='x'
Union All
Select t.id, t.name,t.Parent_id,t.generation,t.gender from family_tree t
join cte c on c. id=t.parent_id
)
,condition
as
(
select Parent_id,COUNT(*) cnt from cte Where generation='z' Group by parent_id having COUNT(*)>1
)
,sibling
as
(
select parent_id,Count(gender) cntg from
(select distinct c.parent_id,c.gender from cte c join condition co on co.parent_id=c.parent_id) a
group by parent_id having count(gender)>1
)
select c.name from cte c join sibling s on c.parent_id=s.parent_id
关于mysql - 层次结构中 SELECT 列与 GROUP BY 列不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41476537/