实现树形结构查询
CREATE TABLE province(
id int4 NOT NULL,
pid int4 NOT NULL,
name VARCHAR(32) NOT NULL,
PRIMARY KEY (id)
);
insert into province (ID, pid, NAME)values (1,0,'山东');
insert into province (ID, pid, NAME)values (2,1,'菏泽');
insert into province (ID, pid, NAME)values (3,1,'济南');
insert into province (ID, pid, NAME)values (4,1,'济宁');
insert into province (ID, pid, NAME)values (5,2,'成武');
insert into province (ID, pid, NAME)values (6,2,'巨野');
insert into province (ID, pid, NAME)values (7,2,'曹县');
insert into province (ID, pid, NAME)values (8,5,'田集');
insert into province (ID, pid, NAME)values (9,5,'南鲁');
insert into province (ID, pid, NAME)values (10,4,'金乡');
insert into province (ID, pid, NAME)values (11,4,'微山');
with RECURSIVE T(id,name,pid,path,depth)as(
select id,name,pid,array[id]as path,1 as depth
from province
where id=1
union all
select b.id,b.name,b.pid,t.path|| b.id,t.depth+1 as depth
from province b
join T on b.pid=T.id
)
SELECT id,name,pid,path,depth from T
ORDER BY depth,id
查询结果