Postgres ANY运算符,在子查询中选择了数组

Eme*_*ski 4 postgresql

有人可以向我解释为什么第四个选择有效,但是前三个不起作用吗?(如果重要的话,我使用的是PostgreSQL 9.3.4。)

drop table if exists temp_a;
create temp table temp_a as
(
    select array[10,20] as arr
);

select 10 = any(select arr from temp_a);    -- ERROR:  operator does not exist: integer = integer[]

select 10 = any(select arr::integer[] from temp_a); -- ERROR:  operator does not exist: integer = integer[]

select 10 = any((select arr from temp_a));  -- ERROR:  operator does not exist: integer = integer[]

select 10 = any((select arr from temp_a)::integer[]);   -- works
Run Code Online (Sandbox Code Playgroud)

这是一个sqlfiddle:http ://sqlfiddle.com/#!15/56a09/2

Den*_*rdy 6

您可能希望获得汇总。根据文档

注意:布尔值聚合,bool_and并且bool_or对应于标准SQL聚合everyanysome。至于任何其他内容,似乎标准语法中都内置了歧义:

SELECT b1 = ANY((SELECT b2 FROM t2 ...)) FROM t1 ...;
Run Code Online (Sandbox Code Playgroud)

如果子查询返回带有布尔值的一行,则ANY可以被视为引入子查询或作为聚合函数。因此,无法为这些聚合指定标准名称。

在Postgres中,该any运算符用于子查询array

前三个查询返回一组类型的值,int[]您正在将它们与进行比较int。不能工作

最后一个查询返回一个int[]数组,但是它只起作用,因为您返回的是单个元素。

展览A;这有效:

select (select i from (values (array[1])) rows(i))::int[];
Run Code Online (Sandbox Code Playgroud)

但这不是:

select (select i from (values (array[1]), (array[2])) rows(i))::int[];
Run Code Online (Sandbox Code Playgroud)

结果如下(相当于您的第四个查询):

select 1 = any((select i from (values (array[1])) rows(i))::int[]);
Run Code Online (Sandbox Code Playgroud)

但这不是(相当于您的第四个查询返回多行):

select 1 = any((select i from (values (array[1]), (array[2])) rows(i))::int[]);
Run Code Online (Sandbox Code Playgroud)

这些也应该起作用,顺便说一句:

select 1 = any(
             select unnest(arr) from temp_a
           );
select 1 = any(
             select unnest(i)
             from (values (array[1]), (array[2])) rows(i)
           );
Run Code Online (Sandbox Code Playgroud)

还要注意该array(select ...))构造,因为它有时很方便:

select 1 = any(array(
             select i
             from (values (1), (2)) rows(i)
           ));
select 1 = any(
             select i
             from (values (1), (2)) rows(i)
           );
Run Code Online (Sandbox Code Playgroud)