如何在PostgreSQL中以数组作为参数进行递归选择

jav*_*irl 3 arrays postgresql recursion select

我试图在PostgreSQL中实现简单的递归函数,但我无法完成它...

我有表MyTable,其中包括列Col1和Col2.里面的数据是这样的:

Col1 | Col2

1 | 2  
2 | 5 
2 | 6
3 | 7
4 | 5
4 | 2
5 | 3
Run Code Online (Sandbox Code Playgroud)

我想写一个函数,它作为Col1 fe(1,2)的参数数组,并给我回Col2这样的值:

1 | 2
2 | 5
2 | 6
Run Code Online (Sandbox Code Playgroud)

然后再次结果:(2,5,6)所以:

1 | 2
2 | 5
2 | 6
5 | 3
Run Code Online (Sandbox Code Playgroud)

(2已经存在,密钥'6'不存在)并且再次(3):

1 | 2
2 | 5
2 | 6
5 | 3
3 | 7
Run Code Online (Sandbox Code Playgroud)

并且(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;
Run Code Online (Sandbox Code Playgroud)

但它当然不起作用

提前致谢

Ant*_*sma 7

递归的基本模式是将基本情况作为联合的第一部分,在第二部分中将递归结果连接到产生下一级结果所需的结果.在你的情况下,它看起来像这样:

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;
Run Code Online (Sandbox Code Playgroud)