1. 程式人生 > 其它 >PostgreSQL的遞迴查詢(with recursive用法)

PostgreSQL的遞迴查詢(with recursive用法)

技術標籤:PostgreSQL資料庫postgresqlsql

WITH語句通常被稱為通用表表達式(Common Table Expressions)或者CTEs。

CTE 優缺點

  • 可以使用遞迴 WITH RECURSIVE,從而實現其它方式無法實現或者不容易實現的遞迴查詢
  • 當不需要將查詢結果被其它獨立查詢共享時,它比檢視更靈活也更輕量
  • CTE只會被計算一次,且可在主查詢中多次使用
  • CTE可極大提高程式碼可讀性及可維護性
  • CTE不支援將主查詢中where後的限制條件push down到CTE中,而普通的子查詢支援

需求

如何實現(省份>城市>區縣)二級聯動效果?

需要對一張地區表進行遞迴查詢,PostgreSQL中有個with recursive

的查詢方式,可以滿足遞迴查詢(一般大於等於2層迴圈巢狀),如下實現:

建立表並插入資料:

create table temp_table(id varchar(3) , pid varchar(3) , name varchar(10)); 

insert into temp_table values('002' , 0 , '浙江省'); 
insert into temp_table values('001' , 0 , '廣東省'); 
insert into temp_table values('003' , '002' , '衢州市');  
insert into temp_table values('004' , '002' , '杭州市') ; 
insert into temp_table values('005' , '002' , '湖州市');  
insert into temp_table values('006' , '002' , '嘉興市') ; 
insert into temp_table values('007' , '002' , '寧波市');  
insert into temp_table values('008' , '002' , '紹興市') ; 
insert into temp_table values('009' , '002' , '台州市');  
insert into temp_table values('010' , '002' , '溫州市') ; 
insert into temp_table values('011' , '002' , '麗水市');  
insert into temp_table values('012' , '002' , '金華市') ; 
insert into temp_table values('013' , '002' , '舟山市');  
insert into temp_table values('014' , '004' , '上城區') ; 
insert into temp_table values('015' , '004' , '下城區');  
insert into temp_table values('016' , '004' , '拱墅區') ; 
insert into temp_table values('017' , '004' , '餘杭區') ; 
insert into temp_table values('018' , '011' , '金東區') ; 
insert into temp_table values('019' , '001' , '廣州市') ; 
insert into temp_table values('020' , '001' , '深圳市') ;

查詢浙江省及以下縣市:

with RECURSIVE cte as 
( 
select a.id,a.name,a.pid from temp_table a where id='002' 
union all  
select k.id,k.name,k.pid from temp_table k inner join cte c on c.id = k.pid 
)
select id,name from cte;

二級聯動效果實現:

with RECURSIVE cte as
(
select a.id,cast(a.name as varchar(100)) from temp_table a where id='002'
union all 
select k.id,cast(c.name||'>'||k.name as varchar(100)) as name  from temp_table k inner join cte c on c.id = k.pid
)
select id,name from cte;