sbe*_*eam 55 postgresql json types jsonb
想要查找某个json列包含空对象的所有行,{}.这可以使用JSON数组,或者如果我在对象中查找特定键.但我只是想知道对象是否为空.似乎找不到会这样做的运营商.
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.
Run Code Online (Sandbox Code Playgroud)
Erw*_*ter 102
有没有平等(或等于)运算符的数据类型json作为一个整体,因为平等是很难建立.jsonb在Postgres 9.4或更高版本中考虑,这是可能的.关于dba.SE(最后一章)的相关答案的更多细节:
SELECT DISTINCT json_column ...或... GROUP BY json_column失败的原因相同(没有相等的运算符).
将表达式的两边都转换为text允许=或<>运算符,但这通常不可靠,因为对于相同的 json值存在许多可能的文本表示.
但是,对于这种特殊情况(空对象),它可以正常工作:
select * from test where foo::text <> '{}'::text;
Run Code Online (Sandbox Code Playgroud)
wei*_*erk 10
空 JSON 数组[]也可能相关。
那么这可以同时适用于[]和{}:
select * from test where length(foo::text) > 2 ;
Run Code Online (Sandbox Code Playgroud)
你必须要小心。将所有数据转换为不同类型以便进行比较,这会在大型数据库上产生性能问题。
如果您的数据具有一致的密钥,那么您可以查找该密钥是否存在。例如,如果计划数据是 {} 或 {id: '1'}
然后你可以寻找没有“id”的项目
SELECT * FROM public."user"
where NOT(plan ? 'id')
Run Code Online (Sandbox Code Playgroud)
从PostgreSQL 9.5开始,这种类型的带有JSON数据的查询是不可能的。另一方面,我同意这将非常有用,并为此创建了一个请求:
https://postgresql.uservoice.com/forums/21853-general/suggestions/12305481-check-if-json-is-empty
随时投票,希望它将得以实施!
| 归档时间: |
|
| 查看次数: |
43497 次 |
| 最近记录: |