我有一个结构表
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 参数的所有值都是数字时,该函数才能正常工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句