postgresql 更新jsonb对象数组中的键值

06odsfpq  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(183)

我有下面的表company,其中jsonb列名为log

|code | log
-----------------------------------------------------------------------------
|K50  | [{"date": "2002-02-06", "type": "Chg Name", "oldvalue": "TEH   "},
         {"date": "2003-08-26", "type": "Chg Name", "oldvalue": "TEOA   "}]
|C44  | [{"date": "2003-05-07", "type": "Chg Name", "oldvalue": "CDE   "}]

字符串
如何修剪oldvalue中的尾随空白?

9udxz4iz

9udxz4iz1#

你可以用jsonb functions and operators的混合来实现:

UPDATE company c
SET    log = sub.log2
FROM  (
   SELECT *
   FROM   company c
   CROSS  JOIN LATERAL (
      SELECT jsonb_agg(jsonb_set(l, '{oldvalue}', to_jsonb(rtrim(l->>'oldvalue')))) AS log2
      FROM   jsonb_array_elements(c.log) l
      ) sub
   WHERE  jsonb_typeof(log) = 'array'  -- exclude NULL and non-arrays
   ) sub
WHERE  c.code =  sub.code   -- assuming code is unique
AND    c.log  <> sub.log2;  -- only where column actually changed.

字符串

SQL Fiddle。

hm2xizp9

hm2xizp92#

在PostgreSQL中,jsonb数据类型用于存储给定的JSON数据。如果你想更新任何嵌套的值,你需要转换代码中的数据,然后才有资格存储在DB中。在这种情况下,尾随空格是无关紧要的。如果你想显式更新,这也是可能的。
PFB链接对此
How to perform update operations on columns of type JSONB

相关问题