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)若当前节点为第二级,即lev值为2,则只需筛选出lev级别为1的记录,这些即为当前节点上级节点的兄弟节点。
(3)对于第三级及以上的情况,需先定位到当前节点的祖父节点(上级的上级),再判断祖父节点下的所有子节点均属于当前节点上级节点的兄弟节点。
最后,使用UNION操作将各部分查询结果合并,形成最终的结果集。
总结
以上内容涵盖了Oracle递归查询的核心用法,希望对各位的学习或工作有所帮助。如有疑问欢迎留言交流,感谢支持。