根据jsonb字段中的多个属性更新Postgres jsonb

时间:2019-10-04 15:04:02

标签: 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')

我在这里错过了明显的东西吗?

1 个答案:

答案 0 :(得分:1)

我想您要在表中插入唯一的idkey组合值。然后,您需要为它们设置唯一的约束:

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

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

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

,只要您在data之后或testtable子句后作为do update set遇到,就可以通过表名(where)限定jsonb列名(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';

btw,data ->> 'appid'='350B79AD'转换为to data ->> 'id'='350B79AD'appid-> id

Demo