Oracle hierarchical query on non-hierarchical data

后端 未结 3 1208
无人及你
无人及你 2021-02-07 13:00

I hava data in an Oracle table that is organized as a graph that can contain cycles (see example).

     CREATE TABLE T (parent INTEGER, child INTEGER)
                   


        
3条回答
  •  萌比男神i
    2021-02-07 13:24

    This might help until visited exceeds 4000 bytes. Cycles should not be possible but the line is there just as an example.

       WITH descendants(node, lvl, pth, visited) AS
        (
        SELECT child node, 1, cast(child as varchar2(4000)), '/'||listagg(child,'/') within group (order by child) over()||'/'
          FROM t 
         where parent = 2
         UNION ALL
        SELECT child, lvl+1, pth||'/'||child, D.visited||listagg(child,'/') within group (order by child) over()||'/'
          FROM T
         INNER JOIN descendants D
            ON T.parent = D.node
         WHERE D.visited not like '%/'||child||'/%'
        )
        cycle node set cyc to '1' default '0' 
        SELECT distinct node
          FROM descendants
         order by node
        ;
    

提交回复
热议问题