? 操作符
dapp_product_beta=# select '{"a":"a","b":{"c":"d"}}'::jsonb ? 'c';
?column?
----------
f
(1 row)
dapp_product_beta=# select '{"a":"a","b":{"c":"d"}}'::jsonb ? 'b';
?column?
----------
t
(1 row)
#仅能判断最外层的是否包含
jsonb::text 变成字符串查询
dapp_product_beta=# select ('{"a":"a","b":{"c":"d"}}'::jsonb)::text ~ '"b":';
?column?
----------
t
(1 row)
select ('{"a":"a","b":[{"c":"d"},{"a":"b"}]}'::jsonb)::text ~ '"b":'
?column?
----------
t
(1 row)
select ('{"a":"a","b":[]}'::jsonb)::text ~ '"b":';
?column?
----------
t
(1 row)
#b为数组的时候,判断有值的sql
select ('{"a":"a","b":[{"c":"d"},{"a":"b"}]}'::jsonb)::text ~ '"b":\[{';
?column?
----------
f
(1 row)
#失败是由于jsonb会格式化
dapp_product_beta=# select ('{"a":"a","b":[{"c":"d"},{"a":"b"}]}'::jsonb)::text;
text
-------------------------------------------
{"a": "a", "b": [{"c": "d"}, {"a": "b"}]}
#修复查询sql为:
dapp_product_beta=# select ('{"a":"a","b":[{"c":"d"},{"a":"b"}]}'::jsonb)::text ~ '"b": \[{';
?column?
----------
t
(1 row)
#B值为数组没有值的情况如下两种
dapp_product_beta=# select '{"a":"a","b":[]}'::jsonb, '{"a":"a"}'::jsonb;
jsonb | jsonb
---------------------+------------
{"a": "a", "b": []} | {"a": "a"}
(1 row)
#故而写出B为数组没有值的判断情况
dapp_product_beta=# select not ('{"a":"a","b":[]}'::jsonb)::text ~ '"b": \[{', not ('{"a":"a"}'::jsonb)::text ~ '"b": \[{';
?column? | ?column?
----------+----------
t | t
#还有一种情况,就是字段a 为jsonb的数组的时候,判断是否为空,需要考虑为null的情况
dapp_product_beta=# select a is null or not a::text ~ '\[{' from table;
?column?
----------
t
(1 row)
其他操作符
https://www.postgresql.org/docs/10/functions-json.html