get ALL last level children (leafs) from a node (hierarhical queries Oracle 11G)

前端 未结 2 1484
轻奢々
轻奢々 2021-01-13 19:40

I am trying and searching the way to get ALL last level children (leafs) from a node, in a hierchical query in Oracle 11g database.

I have 2 tables

相关标签:
2条回答
  • 2021-01-13 20:28

    I think, something like that should do the trick:

    SELECT * FROM
    (SELECT n.id, n.val, CONNECT_BY_ISLEAF isleaf FROM NODES n 
           LEFT JOIN RELATION r ON n.id = r.id_child
    CONNECT BY PRIOR n.id = r.id_father
    START WITH r.id_father IS NULL)
    WHERE isleaf = 1
    

    Oh, and by the way, you can get all leafs without even using hierahical query. Just select all nodes, which are not father's node for any node from relation table. Something like that:

    SELECT n.* FROM NODES n
    WHERE NOT EXISTS (SELECT ID_FATHER FROM RELATION r
                      WHERE r.id_father = n.id)
    

    In order to get the leaf nodes from the specified node, just change condition in START WITH clause, to start tree reverse from the node you're interested in. For example, this query will return you all children leafs of node with id = 5:

    SELECT * FROM
    (SELECT n.id, n.val, CONNECT_BY_ISLEAF isleaf FROM NODES n 
           LEFT JOIN RELATION r ON n.id = r.id_child
    CONNECT BY PRIOR n.id = r.id_father
    START WITH n.id = 5)
    WHERE isleaf = 1
    
    0 讨论(0)
  • 2021-01-13 20:28

    You can simply use CONNECT_BY_ISLEAF.

    SELECT n.id, n.val
    FROM NODES n 
    LEFT JOIN RELATION r ON (n.id = r.id_child)
    WHERE CONNECT_BY_ISLEAF = 1
    CONNECT BY PRIOR n.id = r.id_father
    START WITH r.id_father IS NULL
    
    0 讨论(0)
提交回复
热议问题