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

42次阅读
没有评论

共计 1559 个字符,预计需要花费 4 分钟才能阅读完成。

前言

说到 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 的就是其上级节点的兄弟节点。

(3)其它情况就是 3 以及以上级别,那么就要选查询出来其上级的上级节点(祖父),再来判断祖父的下级节点都是属于该节点的上级节点的兄弟节点。

最后,就是使用 union 将查询出来的结果进行结合起来,形成结果集。

总结

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

向 AI 问一下细节

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-18发表,共计1559字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)