【问题标题】:Postgres - How to check for an empty arrayPostgres - 如何检查空数组
【发布时间】:2010-10-18 18:28:40
【问题描述】:

我正在使用 Postgres,我正在尝试编写这样的查询:

select count(*) from table where datasets = ARRAY[]

即我想知道某列有多少行有一个空数组,但 postgres 不喜欢这样:

select count(*) from super_eds where datasets = ARRAY[];
ERROR:  syntax error at or near "]"
LINE 1: select count(*) from super_eds where datasets = ARRAY[];
                                                             ^

【问题讨论】:

  • ...如果 datasets=NULL 代表 ARRAY[],答案是好的...关于“ARRAY[]”,这是一个语法错误(!):正如 depesz 回答的那样,一个空的数组也需要datatype,Rory的SQL脚本需要修正,是“ARRAY[]::integer”。

标签: sql arrays postgresql


【解决方案1】:

语法应该是:

SELECT
     COUNT(*)
FROM
     table
WHERE
     datasets = '{}'

您使用引号和花括号来显示数组字面量。

【讨论】:

  • 我正在运行 PostgreSQL 9.6.9,虽然“{}”没有错误也没有结果,但“[]”得到了正确的结果。谢谢!
【解决方案2】:

您可以使用 array_upper 和 array_lower 函数,在空数组上返回 null ,所以你可以:

select count(*) from table where array_upper(datasets, 1) is null;

【讨论】:

  • ...如果 datasets=NULL 表示 ARRAY[] 则可以,但是关于“ARRAY[]”,这是一个语法错误 (!)。如何创建一个空数组??
  • 这是错误的,因为它无法判断它的数组关闭的数据类型。添加演员表:选择 ARRAY[]::int4[];
【解决方案3】:

如果你像我一样在 2020 年发现这个问题,那么正确答案是

select count(*) from table where cardinality(datasets) = 0

cardinality 是在 PostgreSQL 9.4 中添加的,也就是 ~2015

https://www.postgresql.org/docs/9.4/functions-array.html

【讨论】:

    【解决方案4】:
    解决方案查询:
    select id, name, employee_id from table where array_column = ARRAY[NULL]::array_datatype;
    
    例子:

    table_emp:

    id (int)| name (character varying) | (employee_id) (uuid[])
    1       | john doe                 | {4f1fabcd-aaaa-bbbb-cccc-f701cebfabcd, 2345a3e3-xxxx-yyyy-zzzz-f69d6e2edddd }
    2       | jane doe                 | {NULL}
    
    
    select id, name, employee_id from tab_emp where employee_id = ARRAY[NULL]::uuid[];
    
        -------
    2       | jane doe                 | {NULL}
    

    【讨论】:

      【解决方案5】:
      SELECT  COUNT(*)
      FROM    table
      WHERE   datasets = ARRAY(SELECT 1 WHERE FALSE)
      

      【讨论】:

        猜你喜欢
        • 2014-09-29
        • 2016-03-09
        • 2011-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-23
        • 1970-01-01
        相关资源
        最近更新 更多