如何让postgres忽略具有重复键的插入,但继续进行 [英] how to have postgres ignore inserts with a duplicate key but keep going

查看:230
本文介绍了如何让postgres忽略具有重复键的插入,但继续进行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将内存中的集合中的记录数据插入到postgres中,并希望数据库忽略数据库中已经存在的任何记录(由于具有相同的主键),但请继续处理其余的插入操作。 / p>

我正在使用clojure和hugsql,但是我猜答案可能与语言无关。



由于我基本上是在以这种方式将数据库视为集合,因此我可能正在使用反模式。

解决方案

使用的是Postgres 9.5或更高版本(自从2016年1月发布以来,我假设您使用的是Postgres 9.5),有一种非常有用的 ON CONFLICT 线索可以使用:

 插入到mytable(id,col1,col2)
值(123,'some_value','some_other_value')
在冲突(id)上不要


I am inserting record data in a collection in memory into postgres and want the database to ignore any record that already exists in the database (by virtue of having the same primary key) but keep going with the rest of my inserts.

I'm using clojure and hugsql, btw, but I'm guessing the answer might be language agnostic.

As I'm essentially treating the database as a set in this way I may be engaging in an antipattern.

解决方案

If you're using Postgres 9.5 or newer (which I assume you are, since it was released back in January 2016), there's a very useful ON CONFLICT cluase you can use:

INSERT INTO mytable (id, col1, col2)
VALUES (123, 'some_value', 'some_other_value')
ON CONFLICT (id) DO NOTHING

这篇关于如何让postgres忽略具有重复键的插入,但继续进行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆