Oracle CONNECT BY recursive child to parent query, include ultimate parent that self references

六眼飞鱼酱① 提交于 2021-02-07 19:58:38

问题


In the following example

id parent_id
A  A
B  A
C  B

select id, parent_id
from table
start with id = 'A'
connect by nocycle parent_id = prior id

I get

A A
B A
C B

In my database I have millions of rows in the table and deep and wide hierarchies and I'm not interested in all children. I can derive the children I'm interested in. So I want to turn the query on its head and supply START WITH with the children ids. I then want to output the parent recursively until I get to the top. In my case the top is where the id and parent_id are equal. This is what I'm trying, but I can't get it to show the top level parent.

select id, parent_id
from table
START WITH id = 'C'
CONNECT BY nocycle id = PRIOR parent_id

This gives me

C B
B A

It's not outputting the A A. Is it possible to do this? What I'm hoping to do is not show the parent_id as a separate column in the output, but just show the name relating to the id. The hierarchy is then implied by the order.


回答1:


I got that result by using WITH clause.

WITH REC_TABLE ( ID, PARENT_ID)
AS
(
    --Start WITH 
    SELECT ID, PARENT_ID
    FROM table
    WHERE ID='C'

    UNION ALL
    --Recursive Block
    SELECT T.ID, T.PARENT_ID
    FROM table T 
    JOIN REC_TABLE R
    ON R.PARENT_ID=T.ID
    AND R.PARENT_ID!=R.ID   --NoCycle rule
)
SELECT *
FROM REC_TABLE;

And it seems to work that way too.

select id, parent_id
from T
START WITH id = 'C'
CONNECT BY id = PRIOR parent_id and parent_id!= prior id;
--                                  ^^^^^^^^^^^^^^^^^^^^
--                                      break cycles

Hope it helps.



来源:https://stackoverflow.com/questions/26439791/oracle-connect-by-recursive-child-to-parent-query-include-ultimate-parent-that

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!