簡體   English   中英

如何刪除 jsonb postgresql 上的數據數組

[英]how to delete data array on jsonb postgresql

如何更新數據庫 postgresql 上jsonb列中的數組數據?

例如,在表table1上,我有具有如下值的列attribute

ID 屬性
1個 [{"task_customs": ["a", "b", "c"]}]
2個 [{"task_customs": ["d", "e", "f"]}]

例如,如果我想從 id 1中刪除b ,那么在attribute列上就會像這樣

ID 屬性
1個 [{"task_customs": ["a", "c"]}]
2個 [{"task_customs": ["d", "e", "f"]}]

已經做了一些研究,但沒有得到我需要的東西..

嘗試這個:

(a) 根據其在數組中的position刪除'b':

UPDATE table1
   SET attribute = attribute #- array['0', 'task_customs', '1'] :: text[]
 WHERE id = 1

(b) 在不知道數組中的 position 的情況下刪除 'b':

WITH list AS
( SELECT id, to_jsonb(array[jsonb_build_object('task_customs', jsonb_agg(i.item ORDER BY item_id))]) AS new_attribute
    FROM table1
   CROSS JOIN LATERAL jsonb_array_elements_text(attribute#>'{0,task_customs}') WITH ORDINALITY AS i(item,item_id)
   WHERE id = 1
     AND i.item <> 'b'
  GROUP BY id
)
UPDATE table1 AS t
   SET attribute = l.new_attribute
  FROM list AS l
 WHERE t.id = l.id

dbfiddle中查看測試結果。

一種選擇是使用jsonb_to_recordset開始拆分 JSONB 值,例如

UPDATE table1 AS t
   SET attribute = 
      (
        SELECT json_build_array(
                            jsonb_build_object('task_customs',task_customs::JSONB - 'b')
                          ) 
          FROM table1,
       LATERAL jsonb_to_recordset(attribute) AS (task_customs TEXT)
         WHERE id = t.id
      ) 
 WHERE id = 1   

演示

編輯:如果您需要評論中表達的更多元素,那么您可以更喜歡使用

UPDATE table1 AS t
   SET attribute = 
      (
        SELECT jsonb_agg(
                    jsonb_build_object(key,je.value::JSONB - 'b')
               ) 
          FROM table1,
       LATERAL jsonb_array_elements_text(attribute) AS atr,
       LATERAL jsonb_each_text(atr::JSONB) AS je
         WHERE id = t.id
      ) 
 WHERE id = 1     

演示

我通過結合 Edouard 和 Barbaros 的答案來解決這個問題

這是我的最終查詢

UPDATE table1 AS t
   SET attribute = 
      jsonb_set(
        attribute,
        '{0,task_customs}',
        (
          SELECT task_customs::JSONB - 'b'
          FROM table1
          CROSS JOIN LATERAL jsonb_to_recordset(attribute) AS (task_customs TEXT)
          WHERE id = t.id
        ) 
      )
WHERE id = 1

dbfiddle中查看測試結果

暫無
暫無

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

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