如何在表中为多个层次结构获取根节点及其所有子节点

时间:2014-03-20 10:39:17

标签: sql database oracle parent-child hierarchy

我在DB

中有以下层次结构
A
|_A1
|  |_A11
|
|_A2

B
|_B1
|
|_B2
   |_B21
   |_B22

我想要一个显示结果为

的查询
Parent    Child
A          A1
A          A11
A          A2
B          B1
B          B2
B          B21
B          B22

1 个答案:

答案 0 :(得分:0)

with w(child, parent) as
(
  select 'A', null from dual
  union all
  select 'A1', 'A' from dual
  union all
  select 'A11', 'A1' from dual
  union all
  select 'A2', 'A' from dual
  union all
  select 'B', null from dual
  union all
  select 'B1', 'B' from dual
  union all
  select 'B2', 'B' from dual
  union all
  select 'B21', 'B2' from dual
  union all
  select 'B22', 'B2' from dual
)
select connect_by_root child parent, child
from w
connect by w.parent = prior w.child
start with w.parent is null
;

返回:

1   A   A
2   A   A1
3   A   A11
4   A   A2
5   B   B
6   B   B1
7   B   B2
8   B   B21
9   B   B22

您可以在where connect_by_root child != childfrom之间添加connect来过滤包含parent == child的行。