首页 > 开发 > Oracle > 正文

Oracle通过递归查询父子兄弟节点方法示例

2019-10-20 13:44:50
字体:
来源:转载
供稿:网友

前言

说到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') awhere b.lev = '1'union allselect *from tmpwhere 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将查询出来的结果进行结合起来,形成结果集。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对CuoXin错新网的支持。


注:相关教程知识阅读请移步到oracle教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表