jsonb查询更新语句

1、jsonb数组查询条件编写

update ne set extattrs=jsonb_set(extattrs, '{snOrMac}', concat('"', 'mac', '"')::jsonb,true)  
where  connectiontypes->0=('"CALLHOME"')::jsonb and extattrs ->>'snOrMac' is null

其中connectiontypes 存值是jsonb 数组类型

2、更新jsonb类型字段中某个键值

比如: 更新pm_001 表 data 字段中的某个值

{
    "oid": "NE{1}CRD{0/0/0}TP{GEI:1}",
    "name": "单板=0/0/0,GEI=1",
    "poId": "null",
    "period": 0,
    "values": {
        "001_001": 0,
        "001_002": 0,
        "001_003": 0,
        "001_004": 0,
        "001_005": 0,
        "001_006": 0,
        "001_007": 0,
        "001_008": 0,
        "001_009": 0,
        "001_010": 0,
        "001_011": 0,
        "001_012": 0
    }
}

json 中 poId的值 更新为 001

update pm_001 set data=jsonb_set(data, '{poId}', '"001"',false)
where data ->>'poId' is null

若更新的值为某个变量值时

update ne set extattrs=jsonb_set(data, '{poId}', concat('"', str, '"')::jsonb,true) where extattrs->>'esn' is not null

若被更新的jsonb字段为空值时,则使用 coalesce 函数

UPDATE sys_user  SET extattrs=  jsonb_set(coalesce(extattrs, '{}'), '{"userName"}',concat('"', 'name' , '"')::jsonb, true);

备注:

介绍下jsonb_set函数

jsonb_set(target jsonb, path text[], new_value jsonb[,create_missing boolean])
target : 这是目的json数据,这里使用内部关联将对应的json查询出来
path : json数据对应的key值
new_value : json数据替换的value值
create_missing : true - 如果不存在对应的key值,则新增,反之,false - 不做其他操作,这里可有可无

介绍下COALESCE函数

COALESCE是返回参数中的第一个非null的值,它要求参数中至少有一个是非null的,如果参数都是null会报错。select COALESCE(null,null); //报错
select COALESCE(null,null,now(),''); //结果会得到当前的时间
select COALESCE(null,null,'',now()); //结果会得到''

//可以和其他函数配合来实现一些复杂点的功能:查询学生姓名,如果学生名字为null或''则显示“姓名为空”
select case when coalesce(name,'') = '' then '姓名为空' else name end from student;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值