本文主要是介绍WITH RECURSIVE as 的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.建表语句
create table TEST(id varchar(3) , pid varchar(3) , name varchar(10));insert into TEST values('002' , 0 , '浙江省');insert into TEST values('001' , 0 , '广东省');
insert into TEST values('003' , '002' , '衢州市');
insert into TEST values('004' , '002' , '杭州市') ;
insert into TEST values('005' , '002' , '湖州市');
insert into TEST values('006' , '002' , '嘉兴市') ;
insert into TEST values('007' , '002' , '宁波市');
insert into TEST values('008' , '002' , '绍兴市') ;
insert into TEST values('009' , '002' , '台州市');
insert into TEST values('010' , '002' , '温州市') ;
insert into TEST values('011' , '002' , '丽水市');
insert into TEST values('012' , '002' , '金华市') ;
insert into TEST values('013' , '002' , '舟山市');
insert into TEST values('014' , '004' , '上城区') ;
insert into TEST values('015' , '004' , '下城区');
insert into TEST values('016' , '004' , '拱墅区') ;
insert into TEST values('017' , '004' , '余杭区') ;
insert into TEST values('018' , '011' , '金东区') ;
insert into TEST values('019' , '001' , '广州市') ;
insert into TEST values('020' , '001' , '深圳市') ;
2.实现效果:
3.实现步骤:
(1)查出浙江省:
select t.id,cast(t.name as varchar(100)) from test t where id='002'
(2)两表拼接查出数据;
with recursive aaa as(select t.id ,cast(t.name as varchar(100)) from test t where id='002'union allselectt.id as tid ,cast(a.name || '>' || t.name as varchar(100)) as namefromtest tinner join aaa a ona.id = t.pid
)
select id,name from aaa
4.原理:
WITH recursive cte_name AS ( 初始语句(非递归部分) UNION ALL 递归部分语句
)
[ SELECT| INSERT | UPDATE | DELETE]
【注意】with as () 后面必须跟着 [ SELECT| INSERT | UPDATE | DELETE] 语句,否则报错
这篇关于WITH RECURSIVE as 的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!