Find the most child node of a parent (any level) in oracle

有些话、适合烂在心里 提交于 2019-12-01 08:09:36

问题


My Table structure is

 | Parent ID   |  ID         |
 |-------------|-------------|
 |      a      |     b       |
 |      b      |     c       |
 |      b      |     d       |
 |      b      |     e       |
 |      c      |     f       |
 |      d      |     g       |
 |      e      |     h       |

I want to get the most child node for all parent . In a other table I have a , b and c . Then I want to get the below result .

 |  Parent_ID  |  Child      |
 |-------------|-------------|
 |      a      |     f       |
 |      a      |     g       |
 |      a      |     h       |
 |      b      |     f       |
 |      b      |     g       |
 |      b      |     h       |
 |      c      |     f       |

f , g , h are the lowest granular .


回答1:


By "most child node" I expect you mean the leaf nodes of the tree. You can determine the leaf nodes with the CONNECT_BY_ISLEAF pseudo column of a hierarchical (CONNECT BY) query.

Given your sample data in a table the following query yields the desired results:

select connect_by_root id id
     , parent_did
  from table1
 where connect_by_isleaf = 1
connect by id = prior parent_did
  start with id in ('a','b','c');

| ID | PARENT_DID |
|----|------------|
|  a |          f |
|  a |          g |
|  a |          h |
|  b |          f |
|  b |          g |
|  b |          h |
|  c |          f |

SQL Fiddle

Taking your updated data and requirements into account including the fact that a second table holds a, b, and c as the start conditions:

select connect_by_root parent_id parent_id
     , id
  from table1
 where connect_by_isleaf = 1
connect by prior id = parent_id
  start with parent_id in (select id from table2)

| PARENT_ID | ID |
|-----------|----|
|         a |  f |
|         a |  g |
|         a |  h |
|         b |  f |
|         b |  g |
|         b |  h |
|         c |  f |

SQL Fiddle You can learn more about hierarchical queries from the documentation.




回答2:


first you should make sure you are using Oracle vision 10g or higher and then use connect_by_isleaf, and you can try to learn more about connect_by

    select connect_by_root a.id as id,a.parent_did
      from table1 a inner join table2 b on a.id=b.id 
       where connect_by_isleaf = '1'
       CONNECT BY PRIOR a.parent_did = a.id;


来源:https://stackoverflow.com/questions/34348681/find-the-most-child-node-of-a-parent-any-level-in-oracle

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