如何通过在oracle中提供子元素ID来获取所有父元素?

时间:2018-07-20 06:16:33

标签: sql oracle oracle11g oracle10g hierarchical-data

我的Oracle表如下

 ID     | ParentID   
 -----------------
 1      |        0  
 2      |        1  
 3      |        2  
 4      |        3  
 5      |        3 

如果我只知道ID并且需要获取oracle中的所有父元素,那么我需要使用什么查询?

例如:-如果我通过5,则需要获得5> 3> 2> 1

2 个答案:

答案 0 :(得分:2)

例如:

SQL> with test (id, parent) as
  2    (select 1, 0 from dual union
  3     select 2, 1 from dual union
  4     select 3, 2 from dual union
  5     select 4, 3 from dual union
  6     select 5, 3 from dual
  7    )
  8  select listagg(id, '->') within group (order by level) result
  9  from test
 10  start with id = &par_id
 11  connect by prior parent = id;
Enter value for par_id: 5

RESULT
---------------------------------------------------------------------
5->3->2->1

SQL>

答案 1 :(得分:1)

您可以使用递归CTE

WITH cte (id, parentid, p) 
     AS (SELECT id, 
                parentid, 
                To_char(id) AS p 
         FROM   t 
         WHERE  id = :p_id --enter 5
         UNION ALL 
         SELECT t.id, 
                t.parentid, 
                c.p 
                || '>' 
                || t.id AS p 
         FROM   t 
                JOIN cte c 
                  ON ( c.parentid = t.id )) 
SELECT p 
FROM   cte 
WHERE  parentid = 0 --Highest parent.

Demo