2

这个问题是关于单行的,而不是一组。我只是好奇使用最新最好的 Pg (9.0) 版本更快,为什么:

基于 PKEY 上的 SELECT 的条件 UPDATE 或 INSERT

尝试插入,在失败时捕获异常并回退到更新

尝试更新,在失败时捕获异常并回退到 INSERT

我认为因为这取决于数据集,所以我们假设三种情况:

  • 50% 的行存在,50% 不存在
  • 存在 100% 的行
  • 100% 的行不存在

存在意味着满足 PKEYs 并且应该更新行。任何有关这方面研究的链接都会很棒。

4

2 回答 2

5

The first scenario will never be faster than the other two, because the SELECT that you issue first is unnecessary additional work and is done implicitely by UPDATE (and possibly INSERT) as well.

Even with a 50% / 50% percent distribution I'd think that using UPDATE/INSERT will slightly be faster as the error handling (catching the exception) takes considerably more time than an UPDATE that does not update anything.

So I'd go for the UPDATE/INSERT pattern unless you know that really a lot (e.g. > 70%) of rows won't be there.

But only a good performance test in your environment can tell that.

于 2011-02-04T18:48:54.037 回答
0

在 postgres 9.5 中,可以执行实际的 upsert:

http://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=168d5805e4c08bed7b95d351bf097cff7c07dd65

INSERT [...] ON CONFLICT DO UPDATE SET [...] WHERE [...]
于 2015-05-08T13:26:02.720 回答