寻找所有的行,其中某个json列包含一个空对象{}。对于JSON数组,或者在对象中寻找特定键,这是可能的。但是我只想知道对象是否为空。似乎找不到可以执行此操作的运算符。# ^! n5 G- W# v! ]$ p
dev=# \d test # P6 L1 }: A" `! a Table "public.test"& O& l1 P( u4 W: I, U
Column | Type | Modifiers& d& S1 V. T& G
--------+------+----------- ; b# B. x% ]6 m% F' C2 s, N& U' J foo | json | / M4 Y9 L! [: o f! P7 I5 L5 Q dev=# select * from test;7 Z2 k6 O- F Z! H
foo # _: G6 q" W% \$ i R --------- ) q& a: j: m' _. b4 e {"a":1} # `+ C6 k, W" p0 y- t {"b":1} 6 z+ V" X& S; L* [0 r {}7 V& Z( ?2 E2 n7 I( v# g
(3 rows) # |, t- T4 i# g Z+ f* s$ f dev=# select * from test where foo != '{}'; E: c" f$ ~ n
ERROR: operator does not exist: json unknown1 ~ ]* ^: d$ c0 p& t: x3 o
LINE 1: select * from test where foo != '{}';1 z! @0 [* T- j
^; B; o2 Y' b" t6 u" D# j6 _$ U0 y
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. 9 H2 r, h- u. B0 x% o6 u. j u1 t dev=# select * from test where foo != to_json('{}'::text);( `% |* e( \0 o
ERROR: operator does not exist: json json 3 @; ]; N9 L1 K! ^ LINE 1: select * from test where foo != to_json('{}'::text);. `" P4 h: ]- Z
^! ]" ]/ g6 J- Z3 K
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.5 T/ M: x7 A1 f3 h. H# w
dwv=# select * from test where foo != '{}'::json;; f5 p3 N5 i1 { N6 K
ERROR: operator does not exist: json json * F9 T4 L% d3 u9 d! ^& H/ T LINE 1: select * from test where foo != '{}'::json;/ h5 _1 Y* o& e4 x/ J
^# i$ O& E6 w9 T' s# a3 Q
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. " j$ E+ C$ F7 E5 p ; [; j8 t! e4 M3 Z, u2 \9 i l 解决方案: 4 W- [& Z) d7 [/ Y & S& [/ L8 ]6 `
/ {& H7 z' I2 U) n0 W8 d; r, h) E+ D5 v
有没有平等(或等于)运算符的数据类型json作为一个整体,因为平等是很难建立。jsonb在可行的情况下,请考虑使用Postgres 9.4或更高版本。有关dba.SE(上一章)的此相关答案中的更多详细信息: 3 \# h9 S$ A! h& n如何从PostgreSQL的JSON []数组中删除已知元素?6 }9 }1 E9 W- s) ~6 r
SELECT DISTINCT json_column ...或... GROUP BY json_column由于相同原因而失败(没有相等运算符)。' M/ X- V$ b/ I( ]; a
将表达式的两边都转换为textallow=或operator,但这通常并不可靠,因为对于相同的JSON值,有很多可能的文本表示形式。 $ `' N) U( T2 r% U# R但是,对于这种特殊情况(空对象),它可以正常工作: g' D$ l$ [* B0 w) Y6 D! }% h9 B. Cselect * from test where foo::text '{}'::text;