pgsql数据库json更新多个key

时间:2024-03-31 14:24:26

json单个key更新

可以使用json_set函数
jsonb_set(target jsonb, path text[], new_value jsonb [, create_missing boolean])
create_missing 为true,如果元素值不存在,则添加create_missing 值为 false:如果元素值不存在,不添加

pgsql数据库json更新多个key

json对象更新

f_info信息 {"name": "xue", "age": "11"}
UPDATE t_test SET f_info = jsonb_set(f_info::jsonb, '{name}', '"John"', true) WHERE f_id = 1
结果: {"name": "John", "age": "11"}

json数组更新

jsonb_set('[{"f1":1,"f2":null},2,3]', '{0,f1}','[2,3,4]', false)

{0,f1}表示更新数组第一个中的f1属性
结果:  [{"f1":[2,3,4],"f2":null},2,3]

json多个key更新

多个key更新利用jsonb的连接操作  ||

pgsql数据库json更新多个key

f_info信息 {"name": "xue", "age": "11","sex":"男"}
UPDATE t_test SET f_info::jsonb || '{"name":"john","sex":"女","score":200}'::jsonb WHERE f_id = 1
结果: {"name": "John", "age": "11","sex":"女","score":200}