更新 jsonb 对象数组中的键值
Update key value in jsonb array of objects
我有以下 table company
和一个名为 log
的 jsonb
列:-
|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 "}]
如何 trim oldvalue
中的尾随空格?
在 postgreSQL 中,jsonb 数据类型用于存储接收到的 json。如果你想更新其中的任何值,你需要先从你的代码中转换数据,然后它有资格存储在数据库中。这是一个很好的做法。在这种情况下,应该从代码中注意尾随空格 itself.If 你想明确更新,这也是可能的。
PFB link 对于那个。
How to perform update operations on columns of type JSONB in Postgres 9.4
您可以混合使用 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.
我有以下 table company
和一个名为 log
的 jsonb
列:-
|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 "}]
如何 trim oldvalue
中的尾随空格?
在 postgreSQL 中,jsonb 数据类型用于存储接收到的 json。如果你想更新其中的任何值,你需要先从你的代码中转换数据,然后它有资格存储在数据库中。这是一个很好的做法。在这种情况下,应该从代码中注意尾随空格 itself.If 你想明确更新,这也是可能的。
PFB link 对于那个。
How to perform update operations on columns of type JSONB in Postgres 9.4
您可以混合使用 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.