错误:JSON类型的输入语法无效

时间:2018-12-03 18:30:57

标签: postgresql

我正在使用PostgreSQL 10.4,并且有2个表:

人:

select distinct a from tbl;
select distinct b from tbl;
select distinct c from tbl;
select distinct d from tbl;

国家/地区:

CREATE TABLE person (
  nationality character varying(100),
  name character varying(100),
  age integer
);

这是我要运行的查询:

CREATE TABLE country (
  demonym character varying(50),
  name character varying(50)
);

这会产生错误:

  

错误:json类型的输入语法无效

     

第11行:WHERE'nationalitiesCount':: json->'1'> 10

     

详细信息:令牌“ nationalitiesCount”无效。

     

上下文:JSON数据,第1行:nationalitiesCount

第二行的第一行select "c"."name", (SELECT row_to_json(r) FROM ( SELECT COALESCE(sum(CASE WHEN p."nationality"='finn' THEN 1 ELSE 0 END),0) as "1", COALESCE(sum(CASE WHEN p."nationality"='spanish' THEN 1 ELSE 0 END),0) as "2" FROM "person" as p WHERE "p"."nationality"="c"."demonym" ) as r) as "nationalitiesCount" from "country" as c WHERE 'nationalitiesCount'::json->'1' > 10 高亮显示为导致错误出现的代码。

问题:如何纠正错误?

1 个答案:

答案 0 :(得分:0)

第一个问题是,对列的引用不应该用单引号引起来,尽管它们可以/有时必须用双引号引起,这就是为什么它不喜欢'nationalitiesCount':: json->'1' 。第二个原因是,列名nationalitiesCount是在查询的SELECT部分​​中定义的,并且不能在定义它的查询的WHERE子句中引用,因此您可以将查询移到子查询中,以便在外部进行引用子查询。

select *
from (select "c"."name",
    (SELECT row_to_json(r) 
     FROM (
      SELECT
       COALESCE(sum(CASE WHEN p."nationality"='finn' THEN 1 ELSE 0 END),0) as "1",
       COALESCE(sum(CASE WHEN p."nationality"='spanish' THEN 1 ELSE 0 END),0) as "2"

       FROM "person" as p
       WHERE "p"."nationality"="c"."demonym"
     ) as r) as "nationalitiesCount"
from "country" as c 
) t
WHERE (t."nationalitiesCount"->>'1')::integer > 10