sql嵌套查询 - 按父级分组结果

时间:2011-05-25 09:35:55

标签: sql oracle nested

我需要从单个表中返回树状结果。目前我使用connect by并开始确保返回所有正确的结果。

select id,parent_id
     from myTable 
 connect by prior id = parent_id start with name = 'manager' 
     group by id, parent_id
 order by parent_id asc

但是我希望结果以树形结构返回。因此,每次找到父行时,其子行将直接显示在其下方。然后转到下一个父母并执行相同的

预期结果

  - Parent A
   - child a
   - child b 
  - Parent B
   - child c
   - child d 

实际结果

- Parent A 
- Parent B
- child a 
- child b 
- child c 
- child d

是否可以在oracle中执行此操作?我的表使用parent_id字段来标识行何时具有父项。每一行都有一个排序顺序,它是应在其父级下排序的顺序和唯一的Id。

我正在使用Oracle DB

2 个答案:

答案 0 :(得分:5)

您想要的是使用ORDER SIBLINGS BY。您拥有的查询是按parent_id列排序,该列覆盖任何层次排序。

以下查询应该按照您的要求执行:

with my_hierarchy_data as (
  select 1 as id, null as parent_id, 'Manager' as name from dual union all
  select 2 as id, 1 as parent_id, 'parent 1' as name from dual union all
  select 3 as id, 1 as parent_id, 'parent 2' as name from dual union all
  select 4 as id, 2 as parent_id, 'child 1' as name from dual union all
  select 5 as id, 2 as parent_id, 'child 2' as name from dual union all
  select 6 as id, 3 as parent_id, 'child 3' as name from dual union all
  select 7 as id, 3 as parent_id, 'child 4' as name from dual 
)
select id, parent_id, lpad('- ', level * 2, ' ') || name as name
from my_hierarchy_data
connect by prior id = parent_id
start with name= 'Manager'
order siblings by parent_id asc

答案 1 :(得分:2)

可以在Oracle分层查询中使用特殊值level。它为层次结构顶层的行返回1,为子节点返回2,依此类推。您可以使用它来创建这样的缩进:

select lpad('- ',level*2,' ') || name
     from myTable 
 connect by prior id = parent_id start with name = 'manager' 
     group by id, parent_id