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 allselect 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 allselect 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 allselect 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)selectsum(n) from t;