postgresql - postgres jsonb_set 多键更新

标签 postgresql jsonb

我有带有 jsonb 列的数据库表。

number  | data
    1   | {"name": "firstName", "city": "toronto", "province": "ON"}

我需要一种更新数据列的方法。 所以我的输出应该是这样的:

{"name": "firstName", "city": "ottawa", "province": "ON", "phone": "phonenum", "prefix": "prefixedName"}

json_set 可以吗? 我添加了如下查询:

update table_name set data = jsonb_set(data, '{city}', '"ottawa"') where number = 1;

但是,我需要一种方法来添加新的键值(如果不存在)并更新键值(如果存在)。是否可以在单个查询中实现这一点?

最佳答案

documentation says :

The || operator concatenates the elements at the top level of each of its operands. ... For example, if both operands are objects with a common key field name, the value of the field in the result will just be the value from the right hand operand.

因此使用您的示例数据:

update table_name set
    data = data || '{"city": "ottawa", "phone": "phonenum", "prefix": "prefixedName"}'
    where number = 1;

此外,如果您要编辑的对象不在顶层 - 只需结合连接和 jsonb_set 函数即可。例如,如果原始数据看起来像

{"location": {"name": "firstName", "city": "toronto", "province": "ON"}}

然后

...
data = jsonb_set(
    data, 
    '{location}', data->'location' || '{"city": "ottawa", "phone": "phonenum", "prefix": "prefixedName"}')
...

关于postgresql - postgres jsonb_set 多键更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38883233/

相关文章:

java - 的用法?在 jsonb 上的 native SQL 查询中

php - 在 PL/pgSQL 中检索 INSERT 的返回行

performance - PostgreSQL-管理用户的联系人-单向或双向关系更好吗?

sql - JSONB 排序聚合

postgresql - 在 Postgres JSONB 中附加键值对的简单方法

sql - 使用 Postgres,如果为 NULL,我如何使用 UPDATE 插入新的 jsonb 值,或者如果值已经存在,如何修改 json?

ruby-on-rails - JSON 哈希值的 bool 属性方法 - Rails 4.2、Postgres JSONB

java - 组织.postgresql.util.PSQLException : ERROR: syntax error at or near ":"

sql - 尝试使用左连接但遇到语法错误,

postgresql - 如何计算Postgres的月底?