with recursive用法

with recursive 则是一个递归的查询子句,他会把查询出来的结果再次代入到查询子句中继续查询。

with recursive d(n, fact) as (
values (1,2)
union all #合并
select n+1, (n+1)*fact from d where n < 5)
SELECT * from d;

在这里插入图片描述

递归过程如下:
n=1 fact=2
n=1,n<5: n=1+1=2,fact=(1+1)*2=4
n=2,n<5:n=2+1=3,fact=(2+1)*4=12
n=3,n<5:n=3+1=4,fact=(3+1)*12=48
n=4,n<5:n=4+1=5,fact=(4+1)*48=240
n=5 n>=5==stop

with recursive d(n, fact) as (
values (1,2)
union all
select n+2, (n+1)*fact from d where n < 5)
SELECT * from d;

![在这里插入图片描述](https://img-blog.csdnimg.cn/30c502c77737402e9c11e9f3787babff.png
递归过程如下:
n=1 fact=2
n=1,n<5: n=1+2=3,fact=(1+1)*2=4
n=3,n<5:n=3+2=5,fact=(3+1)*4=16
n=5 n>=5==stop

with recursive d(n, fact) as (
values (1,2)
union all
select n+2, (n+1)*fact from d where n < 5)
select sum(fact) from d;

在这里插入图片描述
sum(fact)=2+4+16=22

with recursive d(n, fact) as (
values (1,2)
union all
select n+2, (n+1)*fact from d where n < 5)
select sum(n) from d;

在这里插入图片描述sum(n)=1+3+5=9

select * from company;

在这里插入图片描述

with recursive t(n) as (
   values (10)
   union all
   select salary from company where salary < 20000
)
select  * from t;

在这里插入图片描述

with recursive t(n) as (
   values (10)
   union all
   select salary from company where salary < 20000
)
select  sum(n) from t;

在这里插入图片描述

  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值