MyTable的
id | data ___________ 1 |[{"Session1": "", "DeviceId1": ""}, {"Session2": "", "DeviceId2": ""}]
我想要更新数据并将Session1设置为等于xxx而DevicceId1等于yyy
我写了这个查询,但这没效果
update MyTable data=jsonb_set(data, '{Session1}', 'xxx',true)
如何在PostgreSQL中更新json数组的值?
答案 0 :(得分:1)
您可以使用json数组索引(从0开始)作为路径:
update my_table
set data = jsonb_set(data, '{0}', '{"Session1": "xxx", "DeviceId1": "yyy"}')
where id = 1
returning *;
id | data
----+------------------------------------------------------------------------------
1 | [{"Session1": "xxx", "DeviceId1": "yyy"}, {"Session2": "", "DeviceId2": ""}]
(1 row)
答案 1 :(得分:1)
data
是一个json数组,因此Session1
的路径必须为{0,Session1}
,类似{0,DeviceId1}
DeviceId1
哪个会生成更新声明:
UPDATE "MyTable"
SET "data" = jsonb_set(jsonb_set(data, '{0,Session1}', '"xxx"', true), '{0,DeviceId1}', '"yyy"', true)
WHERE id = 1