簡體   English   中英

如何更新 JSONB postgres 列中的整個 JSON 對象,除了 1 個字段

[英]How to update entire JSON object in JSONB postgres column except 1 field

例如我有一張桌子:

CREATE TABLE fruit(id bigint, data jsonb);

例如,一行是:

1,    
{
   "type": "pinapple",
   "store1": {
   "first_added": "<some timestamp>",
   "price": "10",
   "store_id": "1",
   "comments": "some comments..."
},
   "store2": {
   "first_added": "<some timestamp>",
   "price": "11",
   "store_id": "2",
   "comments": "some comments..."
},
   .... more stores
}

在更新的情況下,我有水果 id 和存儲數據:

1,
"store1": {
            "price": "12",
            "store_id": "1",
            "comments": "some comments...V2"
        }

我想更新水果條目中的整個商店對象(對於 store1),除了 first_added 字段。

知道如何通過 JSONB 運算符或函數來完成它嗎?

謝謝

您可以使用

UPDATE fruit
SET data = data || jsonb_set($1::jsonb, '{store1,first_added}', data#>'{store1,first_added}')
WHERE id = 1;

在線演示
其中參數$1設置為值{"store1": {"price": "12", "store_id": "1", "comments": "some comments...V2"}}

或者,如果您需要動態密鑰,請使用

UPDATE fruit
SET data = jsonb_set(data, ARRAY[$2::text], jsonb_set($1::jsonb, '{first_added}', data->$2->'first_added'))
WHERE id = 1;

在線演示

您可以使用jsonb_set函數更改所需的元素,然后使用jsonb_build_object函數創建一個新數據集,然后將數據與||連接起來。 操作員保留其余數據(first_added,...)

update table1 
  set data = jsonb_set(data, '{store1}',  jsonb_build_object('first_added', data->'store1'->'first_added', 'price', 12, 'store_id', 1, 'comments', 'some comments...V2'))
where id  = 1; 

DBfiddle中的演示

暫無
暫無

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

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