Jsonb_set:如何使用键更新所有数组元素

时间:2019-06-11 14:24:01

标签: sql postgresql jsonb

我有一个带有一组列的表“物”

id | name | data
1  | 'hi' | [{name: 'what', amount: 10}, {name:'koo', amount: 15}, {name: 'boo', amount: 13}] 

我想将所有数组元素的数量更改为0。也就是说,我希望结果是

[{name: 'what', amount: 0}, {name:'koo', amount:0}, {name: 'boo', amount: 0}]

当我这样做

UPDATE      things
SET         data = jsonb_set(data, '{0,amount}', '0', false)
WHERE       id=1

这有效,但仅将第一个数组元素数量设置为0。即结果为

[{name: 'what', amount: 0}, {name:'koo', amount: 15}, {name: 'boo', amount: 13}] 

我希望它们都为0。

我该怎么做?

1 个答案:

答案 0 :(得分:-1)

您可以将其拆分,更新并再次放回原处:

select id, 
       name, 
       jsonb_agg(jsonb_set(array_elems, '{amount}', '0')) -- update each element of the array and aggregate them back together
FROM things
JOIN LATERAL (
    select jsonb_array_elements(data) -- split the array into each element
) sub(array_elems) ON TRUE
GROUP BY id, name;
 id | name |                                          jsonb_agg
----+------+---------------------------------------------------------------------------------------------
  1 | hi   | [{"name": "what", "amount": 0}, {"name": "koo", "amount": 0}, {"name": "boo", "amount": 0}]

这是更新表的步骤。

WITH updated_data AS (
  select id, 
       jsonb_agg(jsonb_set(array_elems, '{amount}', '0')) as updated
  FROM things
  JOIN LATERAL (
    select jsonb_array_elements(data) -- split the array into each element
  ) sub(array_elems) ON TRUE
  GROUP BY id
)
UPDATE things set data = updated
FROM updated_data 
WHERE things.id = updated_data.id;