-- 建表
create table jg(
orgid varchar2(20),
porgid varchar2(20)
);
--插入数据
insert into jg values('201','002');
insert into jg values('202','002');
insert into jg values('203','002');
insert into jg values('311','201');
insert into jg values('312','201');
insert into jg values('421','202');
insert into jg values('422','202');
insert into jg values('511','203');
insert into jg values('612','511');
insert into jg values('101','001');
insert into jg values('102','001');
insert into jg values('002','000');
commit;
查询出 002 机构下的所有层级机构
思路:
初始查询:找到所有 PORGID = '002' 的记录(即直接下级)。
递归查询:将每次找到的下级机构作为新的 PORGID,继续查找它们的下级。
终止条件:当没有更多下级时停止。
图片分析
最终代码
with t1(orgid,porgid)as (
select orgid,porgid from jg where porgid = 002
union all
select
shangji.orgid,
shangji.porgid
from t1 yuangong
join jg shangji on shangji.porgid = yuangong.orgid
)
select * from t1;
查询出 511 机构上的所有层级机构
思路:
初始查询:找到 ORGID = '511' 的记录。
递归查询:将每次找到的 PORGID 作为新的 ORGID,继续查找其上级。
终止条件:当 PORGID 为根节点(如 000)或没有上级时停止。
图片分析
最终代码
with t1(orgid,porgid)as (
select orgid,porgid from jg where orgid = 511
union all
select
shangji.orgid,
shangji.porgid
from jg shangji
join t1 yuangong on shangji.orgid = yuangong.porgid
)
select *
from t1;