我正在尝试在 PostgreSQL 中实现简单的递归函数,但我无法完成...
我有表 MyTable,其中包括列 Col1 和 Col2。里面的数据是这样的:
Col1 | Col2
1 | 2
2 | 5
2 | 6
3 | 7
4 | 5
4 | 2
5 | 3
我想编写一个函数,它将 Col1 f.e. 的参数数组作为参数。 (1,2) 并像这样从 Col2 返回值:
1 | 2
2 | 5
2 | 6
然后,再次执行结果:(2, 5, 6) 所以:
1 | 2
2 | 5
2 | 6
5 | 3
(2 已经存在,键 '6' 不存在) 再次 (3):
1 | 2
2 | 5
2 | 6
5 | 3
3 | 7
对于 (7) 什么都没有,因为 Col1 中不存在值“7”。
这是一个简单的递归,但我不知道如何实现它。到目前为止,我有这样的事情:
with recursive aaa(params) as (
select Col1, Col2
from MyTable
where Col1 = params -- I need an array here
union all
select Col1, Col2
from aaa
)
select * from aaa;
但是当然不行
提前致谢
最佳答案
递归的基本模式是将您的基本情况作为并集的第一部分,在第二部分将递归结果加入您需要的结果以产生下一级结果。在您的情况下,它看起来像这样:
WITH RECURSIVE aaa(col1, col2) AS (
SELECT col1, col2 FROM mytable
WHERE col1 = ANY (ARRAY[1,2]) -- initial case based on an array
UNION -- regular union because we only want new values
SELECT child.col1, child.col2
FROM aaa, mytable AS child -- join the source table to the result
WHERE aaa.col2 = child.col1 -- the recursion condition
)
SELECT * FROM aaa;
关于arrays - 如何在 PostgreSQL 中使用数组作为参数进行递归选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12459862/