微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【原创】PostgreSQL 对简单树的遍历

昨天我用MysqL来实现了ORACLE的递归语句CONNECT BY, 看起来稍复杂些。今天来看看POSTGREsql如何实现ORACLE的CONNECT BY。

还是用昨天同样的表以及数据。POSTGREsql自诩最像ORACLE的数据库,所以大部分语句也就都可以简单而且变相的实现了。

在这点上可以用他自己带的WITH递归功能,还可以用第三方扩展带来的类似connect by 函数


先来看第一点,用递归的WITH来展现这棵树的路径。

t_girl=#withrecursivetmp_country(id,path)as
t_girl-#(
t_girl(#selecta.id,'/'||b.nameas"path"fromcountry_relationasainnerjoincountryasbon(a.id=b.id)wherea.parentidisnull
t_girl(#unionall
t_girl(#selecta.id,q.path||'/'||b.nameas"path"fromcountry_relationasainnerjointmp_countryasqon(q.id=a.parentid)
t_girl(#innerjoincountryasbon(a.id=b.id)
t_girl(#)
t_girl-#selecta.pathfromtmp_countryasa;
path
-----------------------------------------------
/Earth
/Earth/northAmerica
/Earth/SouthAmerica
/Earth/Europe
/Earth/Asia
/Earth/Africa
/Earth/Australia
/Earth/northAmerica/Canada
/Earth/northAmerica/CentralAmerica
/Earth/northAmerica/IslandNations
/Earth/northAmerica/UnitedStates
/Earth/northAmerica/UnitedStates/Alabama
/Earth/northAmerica/UnitedStates/Alaska
/Earth/northAmerica/UnitedStates/Arizona
/Earth/northAmerica/UnitedStates/Arkansas
/Earth/northAmerica/UnitedStates/California
(16rows)
Time:3.260ms


还可以用tablefunc扩展带来的CONNECT BY函数把这棵树遍历出来。

由于昨天设计的两张表通过ID来关联,这个扩展自带函数要把名字展现出来比较麻烦,索性这里我就用了一张临时表保存我想要的结果。

t_girl=#CREATETEMPORARYTABLEtmp_country_relationasSELECTb.id,a.name,b.parentid,''::textasparentnameFROMcountryASa,country_relationASbWHEREa.id=b.id;
SELECT16
Time:11.773ms
t_girl=#


这里更新了对应的ID为NAME。

t_girl=#updatetmp_country_relationsetparentname=a.namefromcountryasawhereparentid=a.id;
UPDATE15
Time:1.829ms

我用TABLEFUNC扩展带来的CONNECT BY 实现这棵树的遍历。

t_girl=#selectpathfromconnectby('tmp_country_relationasa','a.name','a.parentname','Earth','/')asg(idtext,parentidtext,levelint,pathtext)orderbylevel;
path
----------------------------------------------
Earth
Earth/Australia
Earth/northAmerica
Earth/Africa
Earth/SouthAmerica
Earth/Europe
Earth/Asia
Earth/northAmerica/IslandNations
Earth/northAmerica/Canada
Earth/northAmerica/CentralAmerica
Earth/northAmerica/UnitedStates
Earth/northAmerica/UnitedStates/California
Earth/northAmerica/UnitedStates/Arkansas
Earth/northAmerica/UnitedStates/Alabama
Earth/northAmerica/UnitedStates/Alaska
Earth/northAmerica/UnitedStates/Arizona
(16rows)
Time:5.974ms
t_girl=#

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐