没有副行的分层查询

问题描述

我有“id-parent_id相关”数据,如下所示:

      1
     / \
    /   \
   2     4
  /
 /
3

我有代码,它返回与特定(与 start with 子句中的条件相关)树相关的所有行的数据 - 在两侧(“向上”和“向下”),例如:>

with
  temp_cte(id,parent_id) as
    (select 1,null from dual
     union all
     select 2,1 from dual
     union all
     select 3,2 from dual
     union all
     select 4,1 from dual
     union all
     select 5,null from dual)
select *
from temp_cte t
connect by nocycle (prior id = parent_id) or (prior parent_id = id)
start with t.id = 2
order by id

如何在没有“侧”(“右”/“左”)行的情况下获取数据? 例如对于上面绘制的 -

当我以 4 开头时,我需要没有 2 or 3 的数据,

当我以 2 and 3 开头时,我需要没有 4 的数据

(如果start with 1,我仍然想要完整的树)

解决方法

这是因为 OR 中的 CONNECT BY 谓词:您的查询双向遍历,因此在 CONNECT BY 的第二步您将拥有父级的所有子级,最后所有的树。

您需要将查询拆分为两个方向的并集。

with
  temp_cte(id,parent_id) as
    (select 1,null from dual
     union all
     select 2,1 from dual
     union all
     select 3,2 from dual
     union all
     select 4,1 from dual
     union all
     select 5,null from dual
)

select id,parent_id
from temp_cte t
where level > 1
connect by nocycle (prior id = parent_id)
start with t.id = 2

union all

select id,parent_id
from temp_cte t
connect by (prior parent_id = id)
start with t.id = 2
order by id
ID | PARENT_ID
-: | --------:
 1 |      null
 2 |         1
 3 |         2

dbfiddle here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...