postgresql complex jsonb update

6ss1mwsb  于 2023-03-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(108)

我需要在PostgreSQL中更新一个jsonb对象,但无法确定更新相同对象的正确语法,下面是相同的用例。

表中数据

Create table jsondata (id int, data jsonb);
INSERT INTO jsondata VALUES 
(1,'[{"cc": null, "subsectionid": 26}, {"cc": null, "subsectionid": 27}]');

SELECT * from jsondata;

用例:

想要更新subsectionid =27的cc的值

查询尝试次数:

UPDATE jsondata
SET data = data || '{null: ["Lake Providence"]}'::jsonb
WHERE data->>'subsectionid' = '27'

请帮助我实现这一点。

ffx8fchx

ffx8fchx1#

我希望有人沿着一个更简单的答案,但这显示了我将如何分解jsonb,然后为更新重新构建它:

with invars as (
  select 27 as subsectionid, 'Lake Providence' as cc
), els as (
  select j.id, ae.rn, 
         case (ae.el->>'subsectionid')::int 
           when i.subsectionid then i.cc
           else ae.el->>'cc' 
         end as cc, 
         ae.el->>'subsectionid' as subsectionid
    from invars i
         cross join jsondata j
         cross join lateral jsonb_array_elements(j.data) with ordinality as ae(el, rn)
   where jsonb_path_exists(j.data, '$[*].subsectionid ? (@ == $x)', 
           jsonb_build_object('x', i.subsectionid))
), newjson as (
  select id, jsonb_agg(els order by rn) - 'id' - 'rn' as newdata
    from els
   group by id
)
update jsondata
   set data = n.newdata
  from newjson n
 where n.id = jsondata.id;

Fiddle

相关问题