gpt4 book ai didi

postgresql - 在 Postgres 中搜索和更新 JSON 数组元素

转载 作者:行者123 更新时间:2023-11-29 14:14:57 24 4
gpt4 key购买 nike

我有一个 Jsonb 列,用于存储如下元素数组:

[ 
{"id": "11", "name": "John", "age":"25", ..........},
{"id": "22", "name": "Mike", "age":"35", ..........},
{"id": "33", "name": "Tom", "age":"45", ..........},
.....
]

我想用一个全新的对象替换第二个对象 (id=22)。我不想一个一个地更新每个属性,因为有很多属性,它们的值都可能已经改变。我只想识别第二个元素并替换整个对象。

我知道有一个 jsonb_set()。但是,要更新第二个元素,我需要知道它的数组索引=1,以便我可以执行以下操作:

jsonb_set(data, '{1}', '{"id": "22", "name": "Don", "age":"55"}',true) 

但我找不到任何方法来搜索和获取该索引。有人可以帮我吗?

最佳答案

我能想到的一种方法是结合 row_numberjson_array_elements:

-- test data
create table test (id integer, data jsonb);
insert into test values (1, '[{"id": "22", "name": "Don", "age":"55"}, {"id": "23", "name": "Don2", "age":"55"},{"id": "24", "name": "Don3", "age":"55"}]');
insert into test values (2, '[{"id": "32", "name": "Don", "age":"55"}, {"id": "33", "name": "Don2", "age":"55"},{"id": "34", "name": "Don3", "age":"55"}]');

select subrow, id, row_number() over (partition by id)
from (
select json_array_elements(data) as subrow, id
from test
) as t;
subrow | id | row_number
------------------------------------------+----+------------
{"id": "22", "name": "Don", "age":"55"} | 1 | 1
{"id": "23", "name": "Don2", "age":"55"} | 1 | 2
{"id": "24", "name": "Don3", "age":"55"} | 1 | 3
{"id": "32", "name": "Don", "age":"55"} | 2 | 1
{"id": "33", "name": "Don2", "age":"55"} | 2 | 2
{"id": "34", "name": "Don3", "age":"55"} | 2 | 3

-- apparently you can filter what you want from here
select subrow, id, row_number() over (partition by id)
from (
select json_array_elements(data) as subrow, id
from test
) as t
where subrow->>'id' = '23';

此外,请考虑您的架构设计。以这种方式存储数据可能不是最好的主意。

关于postgresql - 在 Postgres 中搜索和更新 JSON 数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52324770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com