jsonb字段内部字段查询

? 操作符

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值