pg 递归算法_PostgreSQL递归查询_20191212
前言:Ora2pg處理遞歸查詢并不太好使,特別是當遞歸查詢作為子查詢存在,且引用外層 表字段時,遞歸查詢在pg里的語法是with recursive,寫法不如oracle簡潔,下面介紹轉換語法:
1. 測試表結構
create table trees
(
id int,
code int,--本節點編號
pcode int,--父節點編號
info text
);
-- 插入測試數據
insert into trees values(1,100,null,'course A');
insert into trees values(2,10010,100,'course A10');
insert into trees values(3,1001010,10010,'course A1010');
insert into trees values(4,1001011,10010,'course A1011');
insert into trees values(5,10011,100,'course A11');
insert into trees values(6,10012,100,'course A12');
insert into trees values(7,200,null,'course B');
insert into trees values(8,300,null,'course C');
2. 查詢節點編號10010本級節點下級節點
-- oracle
select *
from trees t
start with t.code = 10010
connect by prior t.code = pcode ;
-- pg
with recursive cte as(
select x.*
from trees x
where x.code = 10010
union all
select y.*
from trees y
join cte c on c.code = y.pcode
)select * from cte;
3. 查詢節點編號10010本級節點上級節點
-- oracle
select *
from trees t
start with t.code = 10010
connect by t.code = prior pcode ;
-- pg
with recursive cte as(
select x.*
from trees x
where x.code = 10010
union all
select y.*
from trees y
join cte c on c.pcode = y.code
)select * from cte;
4. connect by level替換
-- oracle
SELECT REGEXP_SUBSTR(nn, '[^,]+', 1, LEVEL) AS AM
FROM insertmp
CONNECT BY LEVEL <= LENGTH(nn)-LENGTH(REPLACE(nn, ','))+1
-- pg
select distinct regexp_split_to_table(nn,',') am from insertmp;
5. 計算300到500之間的偶數平均值
--不使用遞歸
with cet1 as(
select generate_series(300,500) as a
),cet2 as(
select a from cet1 where a%2=0
)select avg(a) from cet2;
--使用遞歸
with recursive t(n) as(
values(300)
union all
select n+2 from t where n<500
)select avg(n) from t;
往期回顧
總結
以上是生活随笔為你收集整理的pg 递归算法_PostgreSQL递归查询_20191212的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果第四财季电话会议实录:中国手机厂商重
- 下一篇: 输卵管梗阻该怎么治