postgresql 如何使用update语句更新数组中的JSONB列数组

clj7thdc  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(157)

我正在处理postgresql JSONB列,我想在Array中更新Array,这里是我的json,看起来像这样

[
 {
"name": "Arjun",
"artList": [
  {
    "id": 34,
    "category": "Sports",
    "names": [
      {
        "id": 11,
        "label": "Cricket"
      },
      {
        "id": 12,
        "label": "Football"
      },
      {
        "id": 13,
        "label": "Hockey"
      }
    ]
  },
  {
    "id": 35,
    "category": "Entertainment",
    "names": [
      {
        "id": 101,
        "label": "Ancor"
      },
      {
        "id": 102,
        "label": "Comdey"
      },
      {
        "id": 103,
        "label": "Singer"
      }
     ]
    }
   ]
  }
 ]

字符串
要求是从Sports类别的artList中删除Cricket,其中名称为Arjun
这就是我到目前为止所尝试的,但它不起作用。

UPDATE usr
 SET art = s.json_array
  FROM (
     SELECT
       jsonb_agg(
        elems
    ) as json_array
   FROM
    usr p,
    jsonb_array_elements(p.art) elems where   p.name ='Sports' and elems->>'label'<>'Cricket'
 ) s where name ='Arjun'

ni65a41a

ni65a41a1#

使用多个嵌套jsonb_build_object调用:

update js set vals = (select jsonb_agg(case when (v -> 'name')#>>'{}' = 'Arjun' 
    then v ||  jsonb_build_object('artList', 
        (select jsonb_agg(case when (v1 -> 'category')#>>'{}' = 'Sports' 
             then v1 || jsonb_build_object('names', (select jsonb_agg(v2) 
         from jsonb_array_elements(v1 -> 'names') v2 
         where (v2 -> 'label')#>>'{}' != 'Cricket')) else v1 end) 
       from jsonb_array_elements(v -> 'artList') v1)) 
    else v end) 
 from jsonb_array_elements(vals) v)

字符串
See fiddle

相关问题