【问题标题】:How can I modify/update multiple values in a json array如何修改/更新 json 数组中的多个值
【发布时间】:2020-02-10 20:44:02
【问题描述】:

假设我有一个数据库 jsonb 列,其中包含以下格式的 json 数组:

[
  {
    "test1key": "test1Value"
  },
  {
    "test2key": "test2Value"
  },
  {
    "test3key": "test3Value"
  }
]

是否可以在单个查询中更新“test1key”和“test2key”的值?如果有,怎么做?

【问题讨论】:

  • @a_horse_with_no_name 好问题 - 这也是困扰我的事情。是否也可以更新包含多个元素的数组?但至少,就我现在的实现而言,每个数组只有一个元素。
  • 我看到一个包含三个 JSON 元素的数组...
  • 它们应该得到相同的值还是不同的值?请添加预期输出

标签: sql json postgresql jsonb postgresql-9.5


【解决方案1】:

主要问题是为什么你必须这样做? JSON 结构不必要地复杂且不合逻辑。您应该使 JSON 数据尽可能简单。您可以将相同的数据存储在单个对象中:

{"test1key": "test1Value", "test2key": "test2Value", "test3key": "test3Value"}

然后更新就这么简单

update my_table
set json_col = json_col || '{"test1key": "newValue1", "test2key": "newValue2"}'
where id = 1

即使数据来自外部,您也可以随时将其转换为更简单、更高效的形式,然后再保存到数据库中。过于复杂的数据结构使其处理(尤其是更新)变得困难且效率低下:

update my_table t1
set json_col = new_array
from (
    select id, jsonb_agg(jsonb_build_object(old_key, coalesce(new_value, old_value))) as new_array
    from my_table
    cross join jsonb_array_elements(json_col) as a(elem)
    cross join jsonb_each_text(elem) as e(old_key, old_value)
    left join jsonb_each_text(
        '{"test1key": "newValue1", "test2key": "newValue2"}'
        ) as v(new_key, new_value) 
    on old_key = new_key
    group by id
    ) t2
where t1.id = 1 and t2.id = t1.id;

在线演示:db<>fiddle.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-19
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多