在分层查询中查找"最深"的子项

Osw*_*Osw 3 sql oracle connect-by oracle11g transitive-closure-table

我需要一些帮助查询分层数据.这是单个简单的表,其中parent_id引用id,对于根条目可以为null.

  create table edition (
      id           NUMBER(20),
      parent_id    NUMBER(20)
  );
Run Code Online (Sandbox Code Playgroud)

对于表中的每条记录,我需要找到具有最大id的最深的孩子.如果记录没有子节点,则应返回其自己的id.我自己尝试但是在使用START WITH A.id = B.idA和B是子查询的地方失败了,看起来Oracle不允许这样的连接.

以下是示例数据:

     id      parent_id
   ----------------------
      1        NULL
      2           1
      3           1
      4           1
      5           4
      6           5
      7           5
Run Code Online (Sandbox Code Playgroud)

和样本结果

     id      result
   ----------------------
      1           7
      2           2
      3           3
      4           7
      5           7
      6           6
      7           7
Run Code Online (Sandbox Code Playgroud)

Ren*_*ger 5

我相信你想试试

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;
Run Code Online (Sandbox Code Playgroud)