我如何修改/更新json数组中的多个值

问题描述 投票:0回答:1

假设我有一个数据库jsonb列,它具有以下格式的json数组:

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

是否可以在单个查询中更新“ test1key”和“ test2key”的值?如果是这样,如何?

sql json postgresql jsonb postgresql-9.5
1个回答
0
投票

主要问题是您为什么必须这样做? 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.

© www.soinside.com 2019 - 2024. All rights reserved.