首页 > 解决方案 > PostgreSQL:更新多个具有相同名称的内部 jsonb 对象字段

问题描述

我有一个名为的表test,它有 2 列:(id int, md jsonb)md列可以包含这样的数据

{
  "a": {
    ...
    "author": "alice"
    ...
  },
  "b": {
    ...
    "author": "alice"
    ...
  }
}

现在我想更新 to 的所有alice实例bob

我通过做得到了包含行的aliceID

select id from test, lateral jsonb_each(md) where md->>'author' = 'alice';

是否有任何 Postgres 工具来更新包含该author字段的每个内部对象?

任何建议表示赞赏。

标签: postgresqlsql-updatecrudjsonb

解决方案


我同意@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')

db<>fiddle demo


推荐阅读