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;
文章来源:https://www.toymoban.com/news/detail-423429.html
with recursive t(n) as (
values (10)
union all
select salary from company where salary < 20000
)
select sum(n) from t;
文章来源地址https://www.toymoban.com/news/detail-423429.html
到了这里,关于with recursive用法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!