我需要一些帮助来查询分层数据。这是一个简单的表,其中 parent_id
引用 id
并且对于根条目可能为 null。
create table edition (
id NUMBER(20),
parent_id NUMBER(20)
);
对于表中的每条记录,我需要找到具有最大 id 的最深的 child 。如果记录没有 child ,则应返回其自己的 id。我自己尝试过,但使用 START WITH A.id = B.id
失败,其中 A 和 B 是子查询,看起来 Oracle 不允许这样的连接。
这里是示例数据:
id parent_id
----------------------
1 NULL
2 1
3 1
4 1
5 4
6 5
7 5
和一个样本结果
id result
----------------------
1 7
2 2
3 3
4 7
5 7
6 6
7 7
最佳答案
相信你也想试试
create table tq84_edition (
id number primary key,
parent_id number references tq84_edition
);
insert into tq84_edition values ( 1, null);
insert into tq84_edition values ( 2, 1);
insert into tq84_edition values ( 3, 1);
insert into tq84_edition values ( 4, 1);
insert into tq84_edition values ( 5, 4);
insert into tq84_edition values ( 6, 5);
insert into tq84_edition values ( 7, 5);
with x (root, id, parent_id, lvl) as (
select id root,
id,
parent_id,
1 lvl
from tq84_edition
UNION ALL
select x.root root,
tq84_edition.id,
tq84_edition.parent_id,
x.lvl + 1 lvl
from x,
tq84_edition
where x.id = tq84_edition.parent_id
)
select root, max(id) keep (dense_rank last order by lvl, id)
from x
group by root;
关于sql - 在分层查询中查找 "deepest"子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11986533/