首页 > 解决方案 > 在 postgresql 中使用 jsonb_set 更新 jsonb 数组一个没有键的元素

问题描述

我有audits带有 jsonb 字段的表data,它有内容:

"products": [
    {"id": 405, "color": null, "price": 850, "title": "test", "value": 52, "real_value": 105 }, 
    {"id": 347, "color": null, "price": 195, "title": "test2", "value": 69, "real_value": 0}
]

对于更新,需要知道元素的键,但我不知道如何找到该元素的键(0)。例子:

UPDATE audits set data = jsonb_set(data::jsonb,'{"products",0,"real_value"}','125') where id = 10 and enterprise_id = 1;

我尝试使用这个:

SELECT ( select index from generate_series(0, jsonb_array_length(data->'products') - 1) as index where data->'products'->index->>'id' = '347') as index_of_element FROM audits;但这对pg来说是一个非常艰难的操作。

我也知道如何找到这个对象的产品 ID:

select id as possiton from audits where data->'products' @> '[{"id":347}]';但不是在数组中键入(((

也许我可以使用另一个函数来更新数组中的项目,但我不知道如何。

标签: postgresqlsetjsonbarray-key

解决方案


推荐阅读