with recursive用法
Posted 顺毛黑起
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
递归过程如下:
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;
以上是关于with recursive用法的主要内容,如果未能解决你的问题,请参考以下文章