PostgreSQL:更新多个具有相同名称的内部 jsonb 对象字段
PostgreSQL : Update multiple inner jsonb objects fields with same name
我有一个名为 test
的 table,它有 2 列:(id int, md jsonb)
。 md
列可以包含这样的数据
{
"a": {
...
"author": "alice"
...
},
"b": {
...
"author": "alice"
...
}
}
现在我想将 alice
的所有实例更新为 bob
。
我通过
获得了包含 alice
的行的 ID
select id from test, lateral jsonb_each(md) where md->>'author' = 'alice';
是否有任何 Postgres 工具来更新包含 author
字段的每个内部对象?
如有任何建议,我们将不胜感激。
我同意@a_horse_with_no_name 最好检查一下您的存储空间。但是作为一种锻炼来做是很有趣的。我认为唯一的方法是将 json 扩展为 jsonb_each
, updating data with jsonb_set
and then aggregating it back with jsonb_object_agg
:
update test as t set
md = (
select
jsonb_object_agg(
d.key,
case
when d.value->>'author' = 'alice' then
jsonb_set(d.value, '{author}', '"bob"')
else
d.value
end
)
from lateral jsonb_each(t.md) as d
)
where
exists (select * from jsonb_each(t.md) as d where d.value->>'author' = 'alice')
我有一个名为 test
的 table,它有 2 列:(id int, md jsonb)
。 md
列可以包含这样的数据
{
"a": {
...
"author": "alice"
...
},
"b": {
...
"author": "alice"
...
}
}
现在我想将 alice
的所有实例更新为 bob
。
我通过
获得了包含alice
的行的 ID
select id from test, lateral jsonb_each(md) where md->>'author' = 'alice';
是否有任何 Postgres 工具来更新包含 author
字段的每个内部对象?
如有任何建议,我们将不胜感激。
我同意@a_horse_with_no_name 最好检查一下您的存储空间。但是作为一种锻炼来做是很有趣的。我认为唯一的方法是将 json 扩展为 jsonb_each
, updating data with jsonb_set
and then aggregating it back with jsonb_object_agg
:
update test as t set
md = (
select
jsonb_object_agg(
d.key,
case
when d.value->>'author' = 'alice' then
jsonb_set(d.value, '{author}', '"bob"')
else
d.value
end
)
from lateral jsonb_each(t.md) as d
)
where
exists (select * from jsonb_each(t.md) as d where d.value->>'author' = 'alice')