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;