设为首页 加入收藏

TOP

PostgreSQL对简单树的遍历
2014-11-23 22:14:10 来源: 作者: 【 】 浏览:4
Tags:PostgreSQL 简单
昨天我用MySQL来实现了ORACLE的递归语句CONNECT BY, 看起来稍复杂些。今天来看看POSTGRESQL如何实现ORACLE的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函数把这棵树遍历出来。
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=#
t_girl=# update tmp_country_relation set parentname = a.name from country as a where parentid = a.id; UPDATE 15 Time: 1.829 ms
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=#
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇sqlite3脚本的使用 下一篇关于SQL中的字段“包含”与“包含..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: