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

时间:2012-09-17 13:07:28

标签: arrays postgresql select recursion

我试图在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;

但它当然不起作用

提前致谢

1 个答案:

答案 0 :(得分: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;