Recursion In Oracle

前端 未结 2 1760
孤街浪徒
孤街浪徒 2020-11-27 07:40

I have the following table in an oracle:

Parent(arg1, arg2)

and I want the transitive closure of the relation parent. That is, I want the f

相关标签:
2条回答
  • 2020-11-27 07:55

    Oracle allows recursive queries. See: http://www.adp-gmbh.ch/ora/sql/connect_by.html

    Of course, these usually assume the hierarchical data is all in one table. Splitting it into separate tables makes things complicated.

    0 讨论(0)
  • 2020-11-27 08:08
    WITH    Ancestor(arg1, arg2) AS
            (
            SELECT  p.arg1, p.arg2
            FROM    parent p
            WHERE   arg2 NOT IN
            (
                SELECT  arg1
                FROM    parent
            )
    
            UNION ALL
    
            SELECT  p.arg1, a.arg2
            FROM    Ancestor a 
            JOIN    parent p
            ON      p.arg2 = a.arg1
            )
    SELECT  *
    FROM    Ancestor
    

    Oracle only supports recursive CTE since 11g Release 2.

    In earlier versions, use CONNECT BY clause:

    SELECT  arg1, CONNECT_BY_ROOT arg2
    FROM    parent
    START WITH
            arg2 NOT IN
            (
            SELECT  arg1
            FROM    parent
            )
    CONNECT BY
            arg2 = PRIOR arg1
    
    0 讨论(0)
提交回复
热议问题