【问题标题】:How can I get all the parent element by providing child element ID in oracle?如何通过在 oracle 中提供子元素 ID 来获取所有父元素?
【发布时间】:2018-07-20 06:16:32
【问题描述】:

我的 Oracle 表是这样的

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

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

ex:- 如果我通过 5,需要得到 5 > 3 > 2 > 1

【问题讨论】:

    标签: sql oracle oracle11g oracle10g hierarchical-data


    【解决方案1】:

    例如:

    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>
    

    【讨论】:

      【解决方案2】:

      你可以使用递归 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-29
        • 1970-01-01
        • 2019-02-19
        • 2019-07-10
        相关资源
        最近更新 更多