简体   繁体   English

更新 json 数据 PSQL 中的值

[英]Updating value inside json data PSQL

I have a table that contains tables stores in data column as a JSON using psql, trying to update specific cell in the (data column) which is array of objects.我有一个表,其中包含使用 psql 以 JSON 形式存储在数据列中的表,试图更新对象数组(数据列)中的特定单元格。

for example, updating the "first_name":"Fergus" to "first_name":"Marcus" where "id":"1"例如,将 "first_name":"Fergus" 更新为 "first_name":"Marcus" 其中 "id":"1"

CREATE TABLE tables(
    table_id SERIAL PRIMARY KEY,
    table_name VARCHAR(100) NOT NULL,
    user_id VARCHAR(100) NOT NULL,
    data json
);

INSERT INTO tables (table_name, user_id, data)
VALUES (
'Supplier Info', 4, '[
{"id":"1","first_name":"Fergus","last_name":"Flipsen","email":"fflipsen0@ezinearticles.com","gender":"Male"},
 {"id":"2","first_name":"Vincenz","last_name":"Russan","email":"vrussan1@independent.co.uk","gender":"Male"}
]'::JSON);

It is not that easy (and, as commented by a_horse_with_no_name, it would be much simpler with a normalized schema).这并不容易(而且,正如 a_horse_with_no_name 所评论的,使用标准化模式会简单得多)。

Basically, you need to unnest the inner array, modify the relevant object, then aggregate back into an array.基本上,您需要取消嵌套内部数组,修改相关的 object,然后聚合回一个数组。

You can do this with a correlated subquery, jsonb_array_elements() and conditional logic in jsonb_agg() :您可以使用相关子查询、 jsonb_array_elements()jsonb_agg() () 中的条件逻辑来执行此操作:

update tables t
set data = (
    select 
        jsonb_agg(
            case when (x.obj ->> 'id')::int = 1 
                then x.obj || '{"first_name": "Marcus"}'
                else x.obj
            end
            order by x.ord
        ) new_data
    from jsonb_array_elements(t.data) with ordinality x(obj, ord)
)

Demo on DB Fiddle DB Fiddle 上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM