Oracle递归查询父子兄弟节点

1、查询某节点下所有后代节点(包括各级父节点)

1 // 查询id为101的所有后代节点,包含101在内的各级父节点
2 select t.* from SYS_ORG t start with id = '101' connect by parent_id = prior id

2、查询某节点下所有后代节点(不包含各级父节点)

1 select t.*
2   from SYS_ORG t
3  where not exists (select 1 from SYS_ORG s where s.parent_id = t.id)
4  start with id = '101'
5 connect by parent_id = prior id

3、查询某节点所有父节点(所有祖宗节点) 

1 select t.*
2   from SYS_ORG t
3  start with id = '401000501'
4 connect by prior parent_id = id

4、查询某节点所有的兄弟节点(亲兄弟)

1 select * from SYS_ORG t
2 where exists (select * from SYS_ORG s where t.parent_id=s.parent_id and s.id='401000501')

5、查询某节点所有同级节点(族节点),假设不设置级别字段

1 with tmp as(
2       select t.*, level leaf        
3       from SYS_ORG t               
4       start with t.parent_id = '0'     
5       connect by t.parent_id = prior t.id)
6 select *                               
7       from tmp                             
8 where leaf = (select leaf from tmp where id = '401000501');

这里使用两个技巧,一个是使用了level来标识每个节点在表中的级别,还有就是使用with语法模拟出了一张带有级别的临时表

 6、查询某节点的父节点及兄弟节点(叔伯节点)

with tmp as(
    select t.*, level lev
    from SYS_ORG t
    start with t.parent_id = '0'
    connect by t.parent_id = prior t.id)  
select b.*
from tmp b,(select *
            from tmp
            where id = '401000501' and lev = '2') a
where b.lev = '1'
 
union all
 
select *
from tmp
where parent_id = (select distinct x.id
                from tmp x, --祖父
                     tmp y, --父亲
                     (select *
                      from tmp
                      where id = '401000501' and lev > '2') z --儿子
                where y.id = z.parent_id and x.id = y.parent_id); 

这里查询分成以下几步。
首先,将全表都使用临时表加上级别;
其次,根据级别来判断有几种类型,以上文中举的例子来说,有三种情况:
(1)当前节点为顶级节点,即查询出来的lev值为1,那么它没有上级节点,不予考虑。
(2)当前节点为2级节点,查询出来的lev值为2,那么就只要保证lev级别为1的就是其上级节点的兄弟节点。
(3)其它情况就是3以及以上级别,那么就要选查询出来其上级的上级节点(祖父),再来判断祖父的下级节点都是属于该节点的上级节点的兄弟节点。
最后,就是使用union将查询出来的结果进行结合起来,形成结果集。

posted @ 2018-01-12 11:20  dahaihh  阅读(6999)  评论(0编辑  收藏  举报