递归SQL查询 - 以前的ID

问题描述 投票:0回答:1

我有以下表格:

| ID | TYPE  | NAME | PREV_ID |
===============================
| 1  | E     | X1   | 1       |
-------------------------------
| 2  | M     | X2   | 1       |
-------------------------------
| 3  | M     | X2   | 2       |
-------------------------------
| 4  | G     | X3   | 3       |
-------------------------------

所以Prev_Id引用了同一个表的Id。从ID 4开始,我需要完整的“路径”到ID 1.在起始“E”和最后的“C”之间可能有几个类型为“m”的条目,因此列表可能更长甚至更短。是否可以通过一个查询获得完整的连接项链?

sql oracle hierarchical-data recursive-query
1个回答
2
投票

这是典型的分层查询,你唯一需要注意的是,对于id = 1,prev_id也是1,导致无限循环和错误ORA-01436的原因,所以你必须在nocycle查询中添加connect by或在CTE版本中添加条件。

解决方案1:

select t.*, connect_by_root(id)||sys_connect_by_path(prev_id, '=>') path
  from t 
  connect by nocycle id = prior prev_id
  start with id = 4

解决方案2(Oracle 11g或更高版本):

with cte(id, type, name, prev_id, path) as (
    select t.*, id||'=>'||prev_id from t where id = 4
    union all
    select t.id, t.type, t.name, t.prev_id, cte.path||'=>'||t.prev_id 
      from t join cte on t.id = cte.prev_id
      where t.id <> t.prev_id )
select * from cte

两个查询的输出和demo

    ID TYPE NAME    PREV_ID PATH
------ ---- ---- ---------- ---------------
     4 G    X3            3 4=>3
     3 M    X2            2 4=>3=>2
     2 M    X2            1 4=>3=>2=>1
© www.soinside.com 2019 - 2024. All rights reserved.