mysql - 层次结构中 SELECT 列与 GROUP BY 列不同

标签 mysql sql hierarchical-data

我正在使用 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 的姓名。如果我SELECTGROUP 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/

相关文章:

ruby - 将扁平树解析为非扁平树的算法

mysql - 如何使用sql select语句获取两个日期范围内的特定列

mysql - Oracle查询date_add

sql - 表中的最后一个 id 值。数据库服务器

sql - 关于Oracle中多个条件的案例声明

Django 查询选择具有非零子级的父级

php - 将数据库中的开始日期更改为事件的下一次发生是好事还是坏事?

php - 通过 PDO 查询将 MySQL 数据库的每一行存储在一个对象中?

mysql - 优先选择列

sql - 类似于数据库中的引用复制