postgresql - 基于 jsonb 字段中的多个属性更新 postgres jsonb

标签 postgresql jsonb upsert

我正在尝试使用以下查询基于 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')

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

最佳答案

我假设您想将唯一的 idkey 组合值插入表中。然后你需要为他们一个唯一的约束:

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

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

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

并在 do update set 之后或 where 子句作为 testtable.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' 转换为数据 ->> 'id'='350B79AD' ( appid -> id )

Demo

关于postgresql - 基于 jsonb 字段中的多个属性更新 postgres jsonb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238960/

相关文章:

java - MongoDB 3.4 Upsert 不插入

sql - 使用 ON CONFLICT 从 INSERT 返回行而不需要更新

postgresql - 每个表的索引数

sql - 将循环替换为 INSERT/UPDATE 的单个查询

json - 使用动态键和 json 值构建 JSON 对象

json - 从 Postgres JSONB 列中提取值

arrays - 如果条目不包含两个匹配的字段,mongo 添加到嵌套数组

postgresql - 堆栈深度限制 INSERT 触发器

sql - 删除列名中带引号的列

json - 文档存储在现有 PostgreSQL 之上