尝试使用下表在postgresql(9.5.4)中更新/插入JSON记录:
create table (detail jsonb);
insert into table VALUES ('{"name": "tom", "zip": 88717, "city": "dallas"}');
假设我从UI获取了我想要更新/插入的JSON {"name": "tom", "zip": 78717, "city": "houston"}
,同时保持了name字段的唯一性。试过以下但得到错误
ERROR: syntax error at or near "->"
LINE 2: on conflict (detail->'name')
以下是导致错误的SQL语句:
insert into jsonTest VALUES ('{"name": "tom", "zip": 78717, "city": "houston"}')
on conflict (detail->'name')
do update set detail = '{"name": "tom", "zip": 78717, "city": "houston"}'::jsonb where detail->>'name' == 'tom';
答案 0 :(得分:1)
假设您在detail->>'name'
上创建了UNIQUE索引,您的插入内容应如下所示:
insert into jsonTest VALUES ('{"name": "tom", "zip": 78717, "city": "houston"}')
on conflict ((detail->>'name'))
do update set detail = '{"name": "tom", "zip": 78717, "city": "houston"}'::jsonb
我刚刚在on conflict ((detail->>'name'))
添加了另一个括号,并删除了where子句。
编辑:要在detail->>'name'
上创建唯一索引,您可以执行以下操作:
CREATE UNIQUE INDEX jsonTest_name_index ON jsonTest((detail->>'name')) ;
创建索引后,您可以使用" INSERT ON CONFLICT"没有问题。