我有一组这样的数据:
ID NAME PARENT
---- ------ -------
1 Obj #1 NULL
2 Obj #2 1
3 Obj #3 4
4 Obj #4 2
5 Obj #5 3
6 Obj #6 NULL
7 Obj #7 6
因此,如果我想让他们与他们最古老的祖先在一起,我会得到这样的结果:
ID NAME OLDEST
---- ------ -------
1 Obj #1 NULL
2 Obj #2 1
3 Obj #3 1
4 Obj #4 1
5 Obj #5 1
6 Obj #6 NULL
7 Obj #7 6
我将如何进行查询来执行此操作?
最佳答案
由于时间不够,我将只向您提供一种解决方案(这不是最好的解决方案,但适用于使用重复自连接的逻辑,并且只有当您知道层次结构树的上限时).
这是一个有效的 SQL Fiddle.
测试数据生成(就像你的,没有“名称”列):
create table tbl(id int, parent int);
insert into tbl values (1,null),(2,1),(3,4),(4,2),(5,3),(6,null),(7,6);
查询以在层次结构树中找到深度为 5 的最老祖先:
select
t1.id, coalesce(t5.id, t4.id, t3.id, t2.id) as oldest
from tbl t1
left join tbl t2 on t1.parent = t2.id
left join tbl t3 on t2.parent = t3.id
left join tbl t4 on t3.parent = t4.id
left join tbl t5 on t4.parent = t5.id
order by 1;
关于mysql - 如何在 MySQL 中找到最旧的 "ancestor",其中每行都有父行或空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38884849/