sql - 如何在查询的 WHERE 子句中检查 'any or limited'?

标签 sql arrays postgresql plpgsql

我有这个 plpgsql 函数:

CREATE OR REPLACE FUNCTION func_example(
    IN  check_ids      INT [],
    OUT recs           REFCURSOR,
    OUT po_result_code TEXT
) RETURNS RECORD LANGUAGE plpgsql AS $$
BEGIN
    OPEN recs FOR
    SELECT *
    FROM my_table t
      JOIN my_another_table tt on tt.tid = t.id
    WHERE t.enabled = TRUE
          AND tt.some = 1
          AND (
              check_ids IS NULL OR check_ids.count = 0 /* <-- problem here */
              OR t.id = ANY (check_ids)
          );

    po_result_code := 0;
    RETURN;
END;
$$;

调用它会导致错误消息:

Error: [42P01] ERROR: missing FROM-clause entry for table "check_ids"  
SQL state: 42P01

如何检查'argument is null or value in argument'?

一些示例数据:

CREATE TABLE my_table (
    id      INT,
    enabled BOOLEAN DEFAULT TRUE
);
CREATE TABLE my_another_table (
    tid    INT,
    "some" INT DEFAULT 1,
    CONSTRAINT t_another_to_my_fk FOREIGN KEY (tid) REFERENCES my_table (id)
);
INSERT INTO my_table (id, enabled) VALUES (1, TRUE);
INSERT INTO my_another_table (tid, "some") VALUES (1, 1);

最佳答案

为了让 NULL 和空数组通过,替换:

(t.id = ANY (check_ids) OR check_ids IS NULL OR check_ids.count = 0)  -- illegal syntax

用单个表达式:

(t.id = ANY (check_ids) OR <b>(check_ids = '{}') IS NOT FALSE</b>)

这也行,但有点慢:

(t.id = ANY (check_ids) OR check_ids IS NULL OR check_ids = '{}')

与字符串类型密切相关的详细解释:

但是,您的实际问题要求的是不同:

How to check 'argument is null or value in argument'?

这会简化为:

(t.id = ANY (check_ids) OR check_ids IS NULL)

所有这些都属于 SQL 领域,与 PL/pgSQL 无关。

关于sql - 如何在查询的 WHERE 子句中检查 'any or limited'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50346286/

相关文章:

java - 比较java中同一个数组的元素

java - 为什么我的 ListView 呈现重复的项目?

sql索引同列两个方向遍历窗口函数

sql - 如何在插入之前更改触发器函数内复合类型列的值?

php - 从两个不同的数据库查询中查找两个计数列之间的差异并在 PHP 中显示结果

MySQL组计算忽略0状态组

sql - 如何在 SQL Server 中获取 datetime 重复行?

mysql - 根据最低出现值构建表和连接记录

java - 在 JSTL 中浏览二维数组列

java - Hibernate 5 的自定义序列生成器