1

我有两张桌子

node
-------------
id
name

edge
--------------
source_node_id
target_node_id

我也有一个通过查询连接

SELECT level,lpad(' ',4*(level)) || tn.name
FROM Node sn, Node tn, Edge e
where e.source_node_id = sn.id
and e.target_node_id = tn.id
start with e.source_node_id in (0)
connect by prior e.target_node_id = e.source_node_id
union
select 0, name
from Node n
where id in (0)

这正确地给出了如下输出:

0    node1
1        node2
2            node3
2            node4

到目前为止,一切都很好。现在我需要显示每个叶节点的完整层次结构 - 如果需要,重复上层节点......像这样:

0    node1
1        node2
2            node3
0    node1
1        node2
2            node4

我在想也许是 sys_connect_by_path - 但甚至不确定。关于这种输出的最佳生成有什么想法吗?

4

1 回答 1

2

不幸的是,没有提供样本数据,只能猜测。

因此,这是一个仅包含一个表的示例:

-- made up data 
with t1(id1, parent_id, name1) as(
  select 1, null, 'name_1' from dual union all
  select 2, 1,    'name_2' from dual union all
  select 3, 2,    'name_3' from dual union all
  select 4, 2,    'name_4' from dual

), tree as (  -- hierarchical query  
  select id1
       , parent_id
       , concat(lpad('-', level * 3, '-'), name1) as node_name
       , connect_by_isleaf is_leaf
    from t1
   start with parent_id is null
 connect by prior id1 = parent_id
 )

select node_name
   from tree

这会给我们:

NODE_NAME
-----------------
---name_1
------name_2
---------name_3
---------name_4

为了显示每个叶子的完整层次结构,我们开始构建我们的子树

一片叶子,一直到根部:

select node_name
     , row_number() over(partition by connect_by_root(t.id1) 
                         order by id1) as subtree_rn
  from tree t
 start with is_leaf = 1
connect by id1 = prior  parent_id   

结果:

NODE_NAME               SUBTREE_RN
-----------------------------------
---name_1               1
------name_2            2
---------name_3         3
---name_1               1
------name_2            2
---------name_4         3

SQLFiddle 演示

于 2013-08-17T21:19:24.523 回答