萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> PostgreSQL遍歷簡單樹的方法教程

PostgreSQL遍歷簡單樹的方法教程

上次我們講了 MySQL存儲過程實現Oracle鄰接模型樹形處理的方法實例 ,現在我們來看看POSTGRESQL如何實現ORACLE的CONNECT BY。我們可以用PostgreSQL的WITH遞歸遍歷樹。

還是用上次MySQL存儲過程實現Oracle鄰接模型樹形處理的方法實例同樣的表以及數據。POSTGRESQL自诩最像ORACLE的數據庫,所以大部分語句也就都可以簡單而且變相的實現了。

在這點上可以用他自己帶的WITH遞歸功能,還可以用第三方擴展帶來的類似connect by 函數。

 

先來看第一點,用遞歸的WITH來展現這棵樹的路徑。

 代碼如下 復制代碼

t_girl=# with recursive tmp_country(id,path) as
t_girl-# (
t_girl(# select a.id,'/'||b.name as "path" from country_relation as a inner join country as b on (a.id = b.id) where a.parentid is null
t_girl(# union all
t_girl(# select a.id,q.path||'/'||b.name as "path" from country_relation as a inner join tmp_country as q on (q.id = a.parentid)
t_girl(# inner join country as b on (a.id = b.id)
t_girl(# )
t_girl-# select a.path from tmp_country as a;
                     path
-----------------------------------------------
 /Earth
 /Earth/North America
 /Earth/South America
 /Earth/Europe
 /Earth/Asia
 /Earth/Africa
 /Earth/Australia
 /Earth/North America/Canada
 /Earth/North America/Central America
 /Earth/North America/Island Nations
 /Earth/North America/United States
 /Earth/North America/United States/Alabama
 /Earth/North America/United States/Alaska
 /Earth/North America/United States/Arizona
 /Earth/North America/United States/Arkansas
 /Earth/North America/United States/California
(16 rows)


Time: 3.260 ms






還可以用tablefunc擴展帶來的CONNECT BY函數把這棵樹遍歷出來。
由於昨天設計的兩張表通過ID來關聯,這個擴展自帶的函數要把名字展現出來比較麻煩,索性這裡我就用了一張臨時表保存我想要的結果。

 代碼如下 復制代碼

t_girl=# CREATE TEMPORARY TABLE tmp_country_relation as SELECT b.id,a.name,b.parentid,''::text as parentname FROM country AS a,country_relation AS b WHERE a.id = b.id;
SELECT 16
Time: 11.773 ms
t_girl=#




這裡更新了對應的ID為NAME。

 代碼如下 復制代碼
t_girl=# update tmp_country_relation set parentname = a.name from country as a where parentid = a.id;
UPDATE 15
Time: 1.829 ms




我用TABLEFUNC擴展帶來的CONNECT BY 實現這棵樹的遍歷。

 代碼如下 復制代碼


t_girl=# select path from connectby('tmp_country_relation as a','a.name','a.parentname','Earth',0,'/') as g(id text,parentid text,level int,path text) order by level;
                     path
----------------------------------------------
 Earth
 Earth/Australia
 Earth/North America
 Earth/Africa
 Earth/South America
 Earth/Europe
 Earth/Asia
 Earth/North America/Island Nations
 Earth/North America/Canada
 Earth/North America/Central America
 Earth/North America/United States
 Earth/North America/United States/California
 Earth/North America/United States/Arkansas
 Earth/North America/United States/Alabama
 Earth/North America/United States/Alaska
 Earth/North America/United States/Arizona
(16 rows)


Time: 5.974 ms
t_girl=#

 

 

copyright © 萬盛學電腦網 all rights reserved