postgresql - PostgreSQL:更新多个具有相同名称的内部 jsonb 对象字段
问题描述
我有一个名为的表test
,它有 2 列:(id int, md jsonb)
。md
列可以包含这样的数据
{
"a": {
...
"author": "alice"
...
},
"b": {
...
"author": "alice"
...
}
}
现在我想更新 to 的所有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
,用 更新数据,jsonb_set
然后用 聚合回来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')
推荐阅读
- kql - 使用变量调用工作区()进行跨工作区查询
- android - 喷气背包组成。ListItem 中的中心图标
- salesforce - 在 Salesforce 中,是否有任何 API 可以获取已连接应用程序的 IDP URL?
- r - 将不带引号的字符参数列表传递给 apply/map/pmap 调用
- android - “SinchClient 未启动” android studio 中的主要问题
- flutter - Showcase 小部件中的空指针异常
- go - 读取 utf-8 并替换错误
- c# - AutoMapper 工厂方法和声明
- java - 内部连接联合不同数量的列
- javascript - 无法获取 /socket.io/1/