富群兴 网络设计工作室
企业智慧ERP应用软件服务商

postgresql with recursive 递归实现省市区分类查询

 二维码 1461
发表时间:2019-03-24 12:11

递归查询使用CTE

WITH查询的一个重要属性是RECURSIVE,使用RECURSIVE属性可以引用自己的输出,从而实现递归,一般用于层次结构或树状结构的应用场景。

例子如下:

id name  fatherid
1 中国 0
2 湖南省 1
3 广东省 1
4 海南省 1
5 河北省 1
6 河南省 1
7 山东省 1
8 湖北省 1
9 江苏省 1
10 深圳市 3
11 长沙市 2
12 南山区 10
13 衡阳市 2
14 耒阳市 13
15 龙岗区 10
16 福田区 10
17 宝安区 10
...

当给定一个ID时能得到它完整的地名,例如当id=7时,地名是:中国广东省深圳市福田区,当ID=16时,地名是:中国广东省深圳市福田区,这是一个层次数据递归应用场景,可以通过PostgreSQL的WITH查询实现,首先创建表并插入数据,如下:

create table test_area(id int4,name varchar(32),fatherid int4);

insert into test_area values (1,'中国',0);
insert into test_area values (2,'湖南省',1);
insert into test_area values (3,'广东省',1);
insert into test_area values (4,'海南省',1);
insert into test_area values (5,'河北省',1);
insert into test_area values (6,'河南省',1);
insert into test_area values (7,'山东省',1);
insert into test_area values (8,'湖北省',1);
insert into test_area values (9,'江苏省',1);
insert into test_area values (10,'深圳市',3);
insert into test_area values (11,'长沙市',2);
insert into test_area values (12,'南山区',10);
insert into test_area values (13,'衡阳市',2);
insert into test_area values (14,'耒阳市',13);
insert into test_area values (15,'龙岗区',10);
insert into test_area values (16,'福田区',10);
insert into test_area values (17,'宝安区',10);

使用PostgreSQL的with查询检索id为7及以上的所有父节点,如下:

with recursive r as (

select * from test_area where id=16

union all

select test_area.* from test_area,r where test_area.id=r.fatherid

)

select * from r order by id;

查询结果如下:

接下来将结果的name字段合并成“中国广东省深圳市福田区”,可使用php foreach函数遍历实现,这里通过string_agg函数实现,如下:

with recursive r as (

select * from test_area where id=16

union all

select test_area.* from test_area,r where test_area.id=r.fatherid

)

select string_agg(name,'') from (select name from r order by id) n;

结果如下:


本文知识学习自《PostgreSQL实战》page73 74

文章分类: 数据库知识
分享到:
在线留言

在线留言

了解更多软件开发、行业ERP、企业官网应用服务

公司
*
手机
*
描述
*
验证码
 换一张
*
提交留言
联系QQ:2590552134
手机号码:13682478927
联系邮箱:2590552134@qq.com
联系地址:广东省深圳市龙岗区横岗镇新光一街35号
热搜词:ERP软件开发,进销存管理软件免费下载,企业管理软件,企业ERP管理系统
粤公网安备 44030702000841号
我们的使命是助力商家全渠道管理与业务拓展,同时在供应链重塑的背景下,实现商业模式的全新升级
——————
热线电话
136 8247 8927
website qrcode