没有边行的分层查询

hierarchical query without side rows

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

      1
     / \
    /   \
   2     4
  /
 /
3

我有代码,returns 与特定(与 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

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

当我从 2 or 3

开始时,我需要没有 4 的数据

当我从 4

开始时,我需要没有 2 and 3 的数据

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

这是因为 CONNECT BY 中的 OR 谓词:您的查询在两个方向上遍历,因此在 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

db<>fiddle here