您好,登錄后才能下訂單哦!
本篇內容介紹了“怎么用PostgreSQL對樹進行遍歷”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
昨天我用MySQL來實現了ORACLE的遞歸語句CONNECT BY, 看起來稍復雜些。今天來看看POSTGRESQL如何實現ORACLE的CONNECT BY。
還是用昨天同樣的表以及數據。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=#
“怎么用PostgreSQL對樹進行遍歷”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。