说明
一、PostgreSQL案例
在PostgreSQL下使用 conflict。
1、插入更新-案例
(1)表结构
(2)设置唯一键
需要先设置唯一键。(也可以设置多个字段的唯一键)
alter table stu add constraint name_cons unique(name);
如果 没有设置唯一键,错误信息如下:
insert into stu values('王二',35) on conflict(name) do update set age= 35
> ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
> 时间: 0.009s
(3)执行sql
insert into stu values('王二',35) on conflict(name) do update set age=35;
(4)其他案例参考:
insert into tbl (sid, v1, crt_time) values (:sid, :v1, now())
on conflict (sid) do update set
v1=excluded.v1,
crt_time=excluded.crt_time,
cnt=tbl.cnt+1,
sum_v=case tbl.cnt when 1 then tbl.v1+excluded.v1 else tbl.sum_v+excluded.v1 end,
min_v=least(tbl.min_v, excluded.v1),
max_v=greatest(tbl.max_v, excluded.v1)
;
2、批量更新-案例
注意: set 后的字段不用加表名,否者会报错。
update
exam.sc_examstu
set
examstuname = tmp.examstuname,
examstunum = tmp.examstunum
from
(values
<foreach collection="dataList" item="item" separator=",">
(
#{item.idcard},
#{item.fk_examtime},
#{item.examstuname},
#{item.examstunum}
)
</foreach>
) as tmp (idcard,fk_examtime,examstuname