ASP源码.NET源码PHP源码JSP源码JAVA源码DELPHI源码PB源码VC源码VB源码Android源码
当前位置:首页 >> 数据库 >> Oracle >> Oracle通过递归查询父子兄弟节点方法示例

Oracle通过递归查询父子兄弟节点方法示例(1/2)

来源:网络整理     时间:2018-01-22     关键词:

本篇文章主要介绍了" Oracle通过递归查询父子兄弟节点方法示例",主要涉及到方面的内容,对于Oracle感兴趣的同学可以参考一下: 前言说到Oracle中的递归查询语法,我觉得有一些数据库基础的童鞋应该都知道,做项目的时候应该也会用到,下面本文就来介绍下关于Oracle通过递归查询父子兄弟节...

前言

说到Oracle中的递归查询语法,我觉得有一些数据库基础的童鞋应该都知道,做项目的时候应该也会用到,下面本文就来介绍下关于Oracle通过递归查询父子兄弟节点的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

方法如下:

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

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

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

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

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

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

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

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

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

with tmp as(
  select t.*, level leaf  
  from SYS_ORG t    
  start with t.parent_id = '0'  
  connect by t.parent_id = prior t.id)
select *        
  from tmp        
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的就是其上级节点的兄弟节点。

相关图片

相关文章