是否有可能在Postgres中有多个原子的upsert操作?

时间:2018-01-08 14:05:52

标签: sql postgresql transactions atomic upsert

类似于在一个SQL语句中插入多个记录,可以原子地执行多个Upsert吗?

e.g

insert into students ("name","age") values ("sid",23) on conflict ("name") set "age"=12;
insert into students ("name","age") values ("jack",24) on conflict ("name") set "age"=14;
insert into students ("name","age") values ("tom",20) on conflict ("name") set "age"=13;

2 个答案:

答案 0 :(得分:1)

根据documentation以下应该有效:

INSERT INTO students ("name", "age") VALUES ("sid", 23), ("jack",24), ("tom",20)
ON CONFLICT ("name") DO UPDATE SET "age" = EXCLUDED.age;

答案 1 :(得分:0)

是。使用begin和commit语句进行环绕,如下所示:

begin;
insert into students ("name","age") values ("sid",23) on conflict ("name") do update set "age"=12;
insert into students ("name","age") values ("jack",24) on conflict ("name") do update set "age"=14;
insert into students ("name","age") values ("tom",20) on conflict ("name") do update set "age"=13;
commit;

然后这些构成交易。某些语言驱动程序可能有各种方法来处理begin和commit语句,因此如果您不只是尝试使用psql,请在继续之前参考驱动程序的文档。

但是在这方面插入和插入之间没有区别。