用另一个json对象更新json列postgres9.5

时间:2017-10-24 11:27:05

标签: sql json postgresql jsonb

我有一个结构表

id(int) | attributes (json)

1       | {"a":1,"b":2}

我想用另一个json对象

更新属性列
{"b":5, "c":8}

这样最终输出看起来像这样

id(int) | attributes (json)

1       | {"a":1,"b":7, "c":8}

我可以使用||运算符

获得以下结果
id(int) | attributes (json)

1       | {"a":1,"b":5, "c":8}

但不是理想的。

无法为此任务找到任何其他特定功能/操作。

所以任何文档都会有所帮助。

提前致谢。

1 个答案:

答案 0 :(得分:2)

创建自定义函数,例如:

create or replace function json_merge_and_sum(json, json)
returns json language sql as $$
    select json_object_agg(key, sum order by key)
    from (
        select key, sum(value::int) -- or ::numeric
        from (
            select * from json_each_text($1) 
            union 
            select * from json_each_text($2)) a
        group by key
        ) s
$$;

select json_merge_and_sum('{"a":1,"b":2}'::json, '{"b":5, "c":8}'::json);

      json_merge_and_sum       
-------------------------------
 { "a" : 1, "b" : 7, "c" : 8 }
(1 row)

当然,只有当json参数的所有值都是数字时,该函数才能正常工作。