如何使用postgres json字段查询未设置密钥?

时间:2014-06-20 01:24:39

标签: json postgresql

我可以选择与某个json值匹配的记录,例如where properties->>'foo' = 'bar',但是如果键“foo”'还没有设定?我试过where properties->>'foo' IS NULL,但收到错误

No operator matches the given name and argument type(s). You might need to add explicit   type casts.
: SELECT "merchants".* FROM "merchants"  WHERE (properties->>'foo' IS NULL)

1 个答案:

答案 0 :(得分:6)

这是运营商优先问题。 IS NULL绑定比->>更紧密,因此您的代码将被视为properties ->> ('foo' IS NULL)。添加括号 - (properties ->> 'foo') IS NULL

regress=> SELECT '{"a":1}' ->> 'a';
 ?column? 
----------
 1
(1 row)

regress=> SELECT '{"a":1}' ->> 'b';
 ?column? 
----------

(1 row)

regress=> SELECT '{"a":1}' ->> 'b' IS NULL;
ERROR:  operator does not exist: unknown ->> boolean
LINE 1: SELECT '{"a":1}' ->> 'b' IS NULL;
                         ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
regress=> SELECT ('{"a":1}' ->> 'b') IS NULL;
 ?column? 
----------
 t
(1 row)