oracle、sqlServer、postgreSQL、greenplum递归查询

sqlServer、postgreSQL、greenplum递归查询

参考博客:https://blog.csdn.net/wenzhihui_2010/article/details/43935019

递归查询通常可用作将有层级关系的数据进行扁平化展示,如组织机构,包含关系等

1 测试数据创建

--创建表
create table tb(id varchar(3) , pid varchar(3) , name varchar(10)); 

--插入测试数据
insert into tb values('002' , 0 , '浙江省'); 
insert into tb values('001' , 0 , '广东省'); 
insert into tb values('003' , '002' , '衢州市');  
insert into tb values('004' , '002' , '杭州市') ; 
insert into tb values('005' , '002' , '湖州市');  
insert into tb values('006' , '002' , '嘉兴市') ; 
insert into tb values('007' , '002' , '宁波市');  
insert into tb values('008' , '002' , '绍兴市') ; 
insert into tb values('009' , '002' , '台州市');  
insert into tb values('010' , '002' , '温州市') ; 
insert into tb values('011' , '002' , '丽水市');  
insert into tb values('012' , '002' , '金华市') ; 
insert into tb values('013' , '002' , '舟山市');  
insert into tb values('014' , '004' , '上城区') ; 
insert into tb values('015' , '004' , '下城区');  
insert into tb values('016' , '004' , '拱墅区') ; 
insert into tb values('017' , '004' , '余杭区') ; 
insert into tb values('018' , '011' , '金东区') ; 
insert into tb values('019' , '001' , '广州市') ; 
insert into tb values('020' , '001' , '深圳市') ;

2 递归查询语句

2.1 sqlServer递归

with result_table AS (
 select a.id,a.name,a.pid from tb a where id='002' 
 union all  
 select k.id,k.name,k.pid  from tb k inner join result_table c on c.id = k.pid 
) 
select * from result_table;

2.1 gp、postgreSQL递归

with recursive result_table AS (
 select a.id,a.name,a.pid from tb a where id='002' 
 union all  
 select k.id,k.name,k.pid  from tb k inner join result_table c on c.id = k.pid 
) 
select * from result_table;

你可能感兴趣的:(GreenPlum)