我有一个结构表
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}
但不是我们想要的。
无法找到此任务的任何其他特定功能/操作。
因此任何文档都会有所帮助。
提前致谢。
最佳答案
创建自定义函数,例如:
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 参数的所有值都是数字时,该函数才能正常工作。
关于sql - 用另一个 json 对象更新 json 列 postgres9.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46909343/