JSON 类型的 PostgreSQL 错误?

Pet*_*uss 0 postgresql json

此查询不起作用,但错误没有意义

SELECT count(*) FROM t 
WHERE json_typeof(info->'vatids')='array' AND json_array_length(info->'vatids')>1;
Run Code Online (Sandbox Code Playgroud)

错误:无法获得标量的数组长度

PS:同上 JSONb。

a_h*_*ame 5

您没有向我们展示该列中的数据,也没有向我们展示表定义。但我你有这样的事情:

create table t (info json);
insert into t 
  (info)
values
  ('{"vatids" : ["one"]}'),
  ('{"vatids" : ["one", "two"]}'), 
  ('{"vatids" : "n/a"}');
Run Code Online (Sandbox Code Playgroud)

SQL 中没有“短路”条件,WHERE 子句中的所有条件同时(逻辑上)应用,因此json_array_length(info->'vatids')即使您也有json_typeof(info->'vatids')='array',第三行也会失败。

以下也不起作用,因为优化器足够聪明,可以将条件推送到派生表中:

select *
from (
  select info
  from t 
  where json_typeof(info->'vatids') = 'array' 
) x
where json_array_length(info->'vatids') > 1;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您需要一个完全过滤掉无效行的 CTE,只有这样您才能对数组长度应用条件:

with only_arrays as (
  select info
  from t 
  where json_typeof(info->'vatids') = 'array' 
)
select count(*)
from only_arrays
where json_array_length(info->'vatids') > 1;
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为 Postgres 中的 CTE 充当优化栅栏,因此来自外部查询的条件不会被推送到 CTE。大多数时候这是一个缺点,但在这种情况下它确实有帮助。