怎么用PostgreSQL对树进行遍历
本篇内容介绍了“怎么用PostgreSQL对树进行遍历”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
昨天我用MySQL来实现了ORACLE的递归语句CONNECT BY, 看起来稍复杂些。今天来看看POSTGRESQL如何实现ORACLE的CONNECT BY。
还是用昨天同样的表以及数据。POSTGRESQL自诩最像ORACLE的数据库,所以大部分语句也就都可以简单而且变相的实现了。
在这点上可以用他自己带的WITH递归功能,还可以用第三方扩展带来的类似connect by 函数。
先来看第一点,用递归的WITH来展现这棵树的路径。
t_girl=#withrecursivetmp_country(id,path)ast_girl-#(t_girl(#selecta.id,'/'||b.nameas"path"fromcountry_relationasainnerjoincountryasbon(a.id=b.id)wherea.parentidisnullt_girl(#unionallt_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;SELECT16Time:11.773mst_girl=#
这里更新了对应的ID为NAME。
t_girl=#updatetmp_country_relationsetparentname=a.namefromcountryasawhereparentid=a.id;UPDATE15Time:1.829ms
我用TABLEFUNC扩展带来的CONNECT BY 实现这棵树的遍历。
t_girl=#selectpathfromconnectby('tmp_country_relationasa','a.name','a.parentname','Earth',0,'/')asg(idtext,parentidtext,levelint,pathtext)orderbylevel;path----------------------------------------------EarthEarth/AustraliaEarth/NorthAmericaEarth/AfricaEarth/SouthAmericaEarth/EuropeEarth/AsiaEarth/NorthAmerica/IslandNationsEarth/NorthAmerica/CanadaEarth/NorthAmerica/CentralAmericaEarth/NorthAmerica/UnitedStatesEarth/NorthAmerica/UnitedStates/CaliforniaEarth/NorthAmerica/UnitedStates/ArkansasEarth/NorthAmerica/UnitedStates/AlabamaEarth/NorthAmerica/UnitedStates/AlaskaEarth/NorthAmerica/UnitedStates/Arizona(16rows)Time:5.974mst_girl=#
“怎么用PostgreSQL对树进行遍历”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。