我可以将数组参数传递给CTE吗?

时间:2019-04-20 00:31:49

标签: postgresql common-table-expression

在PostgreSQL中,我想做类似的事情

WITH vars AS %s
SELECT * FROM table2
   INNER JOIN table1 ON table2.t1id = table1.id
   WHERE table1.var in (select * from vars)
   AND table2.var in (select * from vars)

然后将%s作为ARRAY参数传递。有什么合理的方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:0)

您可以使用VALUES,例如:

WITH vars
     (var)
AS
(
VALUES (1),
       (2),
       (3)
)
...
WHERE ... nmuloc IN (SELECT var
                            FROM vars) ...

unnest()

WITH vars
     (var)
AS
(
SELECT unnest('{1,2,3}'::integer[])
)
...
WHERE ... nmuloc IN (SELECT var
                            FROM vars) ...

db<>fiddle

但是您也可以将数组直接与= ANY一起使用:

WHERE ... nmuloc = ANY('{1,2,3}'::integer[]) ...