问题
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