我的表结构是
| Parent ID | ID |
|-------------|-------------|
| a | b |
| b | c |
| b | d |
| b | e |
| c | f |
| d | g |
| e | h |
我想获得所有父节点的最多子节点。 在另一张表中,我有a,b和c。然后我想得到以下结果。
| Parent_ID | Child |
|-------------|-------------|
| a | f |
| a | g |
| a | h |
| b | f |
| b | g |
| b | h |
| c | f |
f,g,h是最低的颗粒。
答案 0 :(得分:4)
“大多数子节点”我希望你的意思是树的叶子节点。您可以使用分层(CONNECT_BY_ISLEAF
)查询的CONNECT BY
伪列来确定叶节点。
根据表格中的样本数据,以下查询会产生所需的结果:
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 |
考虑到您更新的数据和要求,包括第二个表格中包含a,b和c作为开始条件的事实:
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 您可以从documentation了解有关分层查询的更多信息。
答案 1 :(得分:0)
首先,您应确保使用Oracle vision 10g或更高版本,然后使用connect_by_isleaf,您可以尝试了解有关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;