如何对表中的多个根节点层次结构进行排序

时间:2019-01-22 16:32:51

标签: sql database oracle parent-child hierarchy

我在数据库中有以下继承关系

A (1)
|_A1 (2)
|  |_A11 (1)
|
|_A2 (1)

B (5)
|_B1 (3)
|
|_B2 (1)
   |_B21 (2)
   |_B22 (3)

我可以得到这样的结果

Parent    Child   Views
A          A1       2
A1         A11      1
A          A2       1
B          B1       3
B          B2       1
B2         B21      2
B2         B22      3

使用以下查询

with w(child, parent, views) as
(
  select 'A', null, 1 from dual
  union all
  select 'A1', 'A', 2 from dual
  union all
  select 'A11', 'A1', 1 from dual
  union all
  select 'A2', 'A', 1 from dual
  union all
  select 'B', null, 5 from dual
  union all
  select 'B1', 'B', 3 from dual
  union all
  select 'B2', 'B', 1 from dual
  union all
  select 'B21', 'B2', 2 from dual
  union all
  select 'B22', 'B2', 3 from dual
)
select parent, child
from w
where level >1
connect by w.parent = prior w.child
start with w.parent is null
;

现在,我希望在以〜开始之前,按('B',null,5)和('A',null,1)之间的视图desc排序,如下所示。

Parent    Child     Views
B          B1         3
B          B2         1   
B2         B21        2
B2         B22        3
A          A1         2
A1         A11        1
A          A2         1

我尝试了更改位置插入查询“ A”和“ B”,但无效。

我可以通过哪种方式搜索层次结构以'B'开头,而不是以'A'开头

我整天都遇到麻烦。请帮助我

0 个答案:

没有答案