且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何模拟“插入忽略”和“关于重复密钥更新” (sql merge)与postgresql?

更新时间:2023-01-22 16:27:39

做一个更新。如果它不修改任何行,意味着它不存在,那么做一个插入。显然,你在一个事务中这样做。

Try to do an UPDATE. If it doesn't modify any row that means it didn't exist, so do an insert. Obviously, you do this inside a transaction.

如果你不想在客户端放置额外的代码,你可以在函数中包装。你也需要一个循环,在这种思维中非常罕见的种族条件。

You can of course wrap this in a function if you don't want to put the extra code on the client side. You also need a loop for the very rare race condition in that thinking.

文档中有一个示例: http://www.postgresql.org/docs/9.3/static/plpgsql-control-structures.html ,示例40-2在底部。

There's an example of this in the documentation: http://www.postgresql.org/docs/9.3/static/plpgsql-control-structures.html, example 40-2 right at the bottom.

这通常是最简单的方法。你可以做一些魔法与规则,但它可能会是一个更麻烦。我建议在任何一天的换行函数方法。

That's usually the easiest way. You can do some magic with rules, but it's likely going to be a lot messier. I'd recommend the wrap-in-function approach over that any day.

这适用于单行或几行的值。如果你处理大量的行,例如从一个子查询,你***把它分成两个查询,一个用于INSERT和一个UPDATE(当然是一个合适的连接/子查询 - 不需要写你的主过滤器两次)

This works for single row, or few row, values. If you're dealing with large amounts of rows for example from a subquery, you're best of splitting it into two queries, one for INSERT and one for UPDATE (as an appropriate join/subselect of course - no need to write your main filter twice)