查找某个 json 列包含空对象 {}
的所有行。这对于 JSON 数组是可能的,或者如果我正在寻找对象中的特定键。但我只想知道对象是否为空。似乎找不到可以执行此操作的运算符(operator)。
dev=# \d test
Table "public.test"
Column | Type | Modifiers
--------+------+-----------
foo | json |
dev=# select * from test;
foo
---------
{"a":1}
{"b":1}
{}
(3 rows)
dev=# select * from test where foo != '{}';
ERROR: operator does not exist: json <> unknown
LINE 1: select * from test where foo != '{}';
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
dev=# select * from test where foo != to_json('{}'::text);
ERROR: operator does not exist: json <> json
LINE 1: select * from test where foo != to_json('{}'::text);
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
dwv=# select * from test where foo != '{}'::json;
ERROR: operator does not exist: json <> json
LINE 1: select * from test where foo != '{}'::json;
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
最佳答案
对于数据类型 json
没有等式(或不等式)运算符 作为一个整体,因为平等很难建立。考虑 jsonb
在 Postgres 9.4 或更高版本中,这是可能的。有关 dba.SE(最后一章)的相关答案中的更多详细信息:
SELECT DISTINCT json_column ...
或 ... GROUP BY json_column
由于同样的原因失败(没有相等运算符)。
将表达式的两边都转换为 text
允许 =
或 <>
运算符,但这通常不可靠,因为 same JSON 值有许多可能的文本表示。在 Postgres 9.4 或更高版本中,转换为 jsonb
反而。 (或使用 jsonb
开头。)
然而,对于这种特殊情况(空对象)它工作得很好:
select * from test where foo::text <> '{}'::text;
https://stackoverflow.com/questions/24292575/