日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

pg 递归算法_PostgreSQL递归查询_20191212

發布時間:2024/9/18 数据库 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。