请向我解释这种行为。
此 SQL 查找 ids (type is array::bigint
) 为空的元素。
SELECT * FROM rises WHERE ids = '{}'
-- finds, e.g., 9 rows
Run Code Online (Sandbox Code Playgroud)
此 SQL 未找到任何行:
SELECT * FROM rises WHERE array_length(ids, 1) = 0
--finds always 0 rows
Run Code Online (Sandbox Code Playgroud)
但是这个 SQL 可以找到非空数组
SELECT * FROM rises WHERE array_length(ids, 1) > 0
--finds, e.g., 15 rows
Run Code Online (Sandbox Code Playgroud)
初始化:
CREATE TABLE rises(
id bigserial,
d1 bigint DEFAULT 0,
ids bigint[] DEFAULT '{}',
PRIMARY KEY (id));
Run Code Online (Sandbox Code Playgroud)
为什么array_length
可以找到非空数组,但对空数组不起作用?
小智 8
看起来 PostgreSQL 返回NULL
空数组。尝试:
SELECT
array_length(ARRAY[]::bigint[], 1),
array_length(ARRAY[]::bigint[], 1) IS NULL,
array_lower(ARRAY[]::bigint[], 1),
array_upper(ARRAY[]::bigint[], 1)
Run Code Online (Sandbox Code Playgroud)
你得到:
null|true|null|null
看起来很奇怪,但这就是它的方式。解决方法是使用COALESCE
:
SELECT
COALESCE(array_length(ARRAY[]::bigint[], 1), 0)
Run Code Online (Sandbox Code Playgroud)
返回 0。
在 PostgreSQL 9.4 上试过这个。