簡體   English   中英

Jsonb_set:如何使用鍵更新所有數組元素

[英]Jsonb_set: How to Update ALL array elements with key

我有一個帶有一組列的表“物”

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。

我怎么做?

您可以將其拆分,更新並再次放回原處:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM