oracle connect by 转postgresql with recursive 的初步认识

近期公司需要将oracle转成postgresql,现总结如下:

//code是本级编号,srd_code是上级编号

查询本级以及下级:
select * 
from student t
start with t.code = '16120624' 
connect by prior t.code = srd_code 

查询本级以及上级:
select *
from student t
start with t.code = '16120624'
connect by t.code = prior srd_code 

查询本级以及下级:
with recursive cte as(
    select x.* 
    from student x
    where x.code = '16120624'
    union all 
    select y.*
    from student y
    join cte c on c.code = y.srd_code and y.srd_code = '16120624'
)select code from cte

现在尚且还没有想出查询本级以及上级的代替方式,如果有欢迎各位补充教我一下,谢谢

考虑到没有数据没有参考性,现给出如下数据: 

 这里查出了习水县以及其下面所有部门

查阅了一下资料,连同本级向上查询的方法如下:

with recursive cte as(
    select x.* from student x where x.code = '1612624'
    union all
    select y.* from student y,cte where y.code = cte.srd_code 
)select * from cte


这里查出了连同习水县及其以上的单位 

不足之处望大神批评指正

猜你喜欢

转载自blog.csdn.net/qq_40894047/article/details/83545836