【发布时间】:2020-08-17 17:53:18
【问题描述】:
我正在尝试解决一个问题以使用 SQL 生成斐波那契数列。通过我的方法,查询在大约第 21 次迭代调用后通过一系列union all 对它的函数进行超时。
create function f(bigint) returns bigint
as 'select case
when $1 = 0 then 0
when $1 = 1 then 1
when $1 = 2 then 1
when $1 = 3 then 2
else f($1-1) + f($1-2)
end;'
language sql
immutable
returns null on null input;
当前查询将 f(n) 生成为表中的行:
select f(0) as x
union all
select f(1) as x
union all
select f(2) as x
union all
...
select f(21) as x
generate_series(start, end) 和 f(start),f(end) 可以以某种方式被利用吗?确实尝试过这种方法,但它似乎不起作用,因为它只是从头到尾返回结果,而不是斐波那契序列本身。
欢迎任何建议或替代方法。谢谢。
【问题讨论】:
-
我确实尝试了一个类似于第一个链接的链接,但首先是为了我自己的角度。
标签: sql postgresql recursion