优化Oracle中的层次结构查询

时间:2016-04-08 02:30:56

标签: sql oracle performance hierarchical-data

表"链接"包含2列:PARENT_CODE,CHILD_CODE

PARENT_CODE | CHILD_CODE 
------------|------------
A1          | B1 
A1          | B2
B1          | C1 
B1          | C2 
B2          | C3 
B3          | C3
C3          | D1

此表最终用于形成以下图表:

node structure

我的问题是如何在Oracle中编写优化的层次结构查询以获得连接的完整图形,输入参数将是任何节点。

为了说明输入/输出,这是简化的SQL: 从{HIERARCHY QUERY}中选择PARENT_CODE,CHILD_CODE,其中NODE = {ANY NODE}

1 个答案:

答案 0 :(得分:0)

下面的查询显示了所有链接。我的想法是首先在节点之间创建两种方式的连接。使用它我们可以做返回我们的结果的递归查询。最后一件事是解码,返回谁是真正的父母,谁是基于dir的孩子(0 - 表示原始方向,1 - 表示恢复方向)。

with linkT (parent_code, child_code) as 
(select 'A1','B1' from dual union all
 select 'A1','B2' from dual union all
 select 'B1','C1' from dual union all
 select 'B1','C2' from dual union all
 select 'B2','C3' from dual union all
 select 'B3','C3' from dual union all
 select 'C3','D1' from dual union all
 select 'E1','F1' from dual ),
T1 as (
select parent_code, child_code, 0 Dir from linkT
union all 
select child_code, parent_code, 1 Dir from linkT )
select distinct 
       decode(dir, 0, parent_code, child_code) as Parent_code,
       decode(dir, 0, child_code, parent_code) as Child_Code
from (
select parent_code, child_code, dir
from T1 x
start with x.child_code='A1'
connect by nocycle prior x.parent_code=x.child_code ) 
order by 1,2