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

标签 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}

但不是我们想要的。

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

因此任何文档都会有所帮助。

提前致谢。

最佳答案

创建自定义函数,例如:

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/

相关文章:

sql - 使用闪回查询时出现 BST 到 GMT Oracle 错误 (ORA-08186)

mysql - 从数据库中选择所有有喜欢和没有喜欢的人

python - 从python中的JSON字符串中提取特定值

跨多个列的 PostgreSQL 唯一值

sql - 建议一种有效的查询方式

php - 在 mysql 中使用 where 条件选择以前的 id

javascript - 从 REST API 读取 JSON 响应始终返回空文本

javascript - 将类添加到 span 元素不起作用

sql - SQL 中的简单 CASE 表达式

postgresql - 当某些列是时间戳时,如何插入值?