【问题标题】:Upserting a postgres jsonb based on multiple properties in jsonb field更新基于 jsonb 字段中的多个属性的 postgres jsonb
【发布时间】:2019-10-09 00:38:36
【问题描述】:

我正在尝试使用以下查询根据 jsonb 字段中的多个 json 属性将 jsonb 字段插入到表中

insert into testtable(data) values('{
    "key": "Key",
    "id": "350B79AD",
    "value": "Custom"
}')
On conflict(data ->>'key',data ->>'id')
do update set data =data || '{"value":"Custom"}'
WHERE data ->> 'key' ='Key' and data ->> 'appid'='350B79AD'

上面的查询抛出如下错误

ERROR:  syntax error at or near "->>"
LINE 8: On conflict(data ->>'key',data ->>'id')

我在这里遗漏了什么明显的东西吗?

【问题讨论】:

  • 冲突目标必须是唯一的约束,或者作为快捷方式,必须是唯一的列。您不能选择 jsonb 对象的一部分。
  • 所以。似乎唯一的方法是先获取 json 并更新或插入?

标签: postgresql jsonb upsert


【解决方案1】:

我想您想在表中插入唯一的 id 和 key 组合值。然后你需要一个唯一的约束:

create unique index on testtable ( (data->>'key'), (data->>'id') );

并且还为on conflict 子句使用额外的括号作为元组:

on conflict( (data->>'key'), (data->>'id') )

并在do update set 或where 子句之后遇到testtable.data 时,通过表名(testtable)限定jsonb 列名(data)。因此,将您的语句转换为:

insert into testtable(data) values('{
    "key": "Key",
    "id": "350B79AD",
    "value": "Custom1"
}')
    on conflict( (data->>'key'), (data->>'id') )
    do update set data = testtable.data || '{"value":"Custom2"}'
 where testtable.data ->> 'key' ='Key' and testtable.data ->> 'id'='350B79AD';

顺便说一句,data ->> 'appid'='350B79AD' 转换为 to data ->> 'id'='350B79AD' (appid -> id)

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2023-01-29
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多