更新数组 json 的数据
Update data of array json
我的表格
id | data
___________
1 |[{"Session1": "", "DeviceId1": ""}, {"Session2": "", "DeviceId2": ""}]
我要更新数据并设置 Session1 等于 xxx 和 DevicceId1 等于 yyy
我写了这个查询但是没用
update MyTable data=jsonb_set(data, '{Session1}', 'xxx',true)
如何在 PostgreSQL 中更新 json 数组的值?
你可以使用一个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)
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
我的表格
id | data ___________ 1 |[{"Session1": "", "DeviceId1": ""}, {"Session2": "", "DeviceId2": ""}]
我要更新数据并设置 Session1 等于 xxx 和 DevicceId1 等于 yyy
我写了这个查询但是没用
update MyTable data=jsonb_set(data, '{Session1}', 'xxx',true)
如何在 PostgreSQL 中更新 json 数组的值?
你可以使用一个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)
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