gpt4 book ai didi

postgresql - 在循环中通过键从 jsonb 数组中删除属性

转载 作者:行者123 更新时间:2023-11-29 13:11:23 25 4
gpt4 key购买 nike

我尝试通过循环中的 jsonb 数组中的键删除属性

groups = '
[
{"id": "1", "name": "Ann", "age": 20 },
{"id": "2", "name": "Margaret", "age": 30 }
]';

FOR i IN 0..(jsonb_array_length(groups) - 1)
LOOP
groups = groups - '{age}';
END LOOP;

/* but nothing happened, I see [{"id": "1", "age": 20, "name": "Ann"}, {"id": "2", "age": 30, "name": "Margaret"}] */

RAISE NOTICE '%', groups;

但什么也没发生。我该怎么做?

最佳答案

在循环的每一步你只能修改数组的一个元素,所以你必须使用一个新的变量来聚合结果:

do $$
declare
groups jsonb =
'[
{"id": "1", "name": "Ann", "age": 20 },
{"id": "2", "name": "Margaret", "age": 30 }
]';
new_groups jsonb = '[]';
begin
for i in 0..jsonb_array_length(groups) - 1
loop
new_groups:= new_groups || (groups->i) - 'age';
end loop;
raise notice '%', new_groups;
end $$;

NOTICE: [{"id": "1", "name": "Ann"}, {"id": "2", "name": "Margaret"}]
DO

更好的选择是在没有循环和附加变量的单个查询中执行相同的操作:

do $$
declare
groups jsonb =
'[
{"id": "1", "name": "Ann", "age": 20 },
{"id": "2", "name": "Margaret", "age": 30 }
]';
begin
select jsonb_agg(value- 'age')
from jsonb_array_elements(groups)
into groups;
raise notice '%', groups;
end $$;

关于postgresql - 在循环中通过键从 jsonb 数组中删除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54204702/

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