选择count(*)vs保留一个计数器

Lou*_*Lou 5 sql performance counting

假设已放置索引,并且绝对计数精度不是必需的(可以将其减少一到两个),则可以使用:

选项A

select count(*) 
  from Table 
 where Property = @Property
Run Code Online (Sandbox Code Playgroud)

选项B

update PropertyCounters
   SET PropertyCount = PropertyCount + 1  
 where Property = @Property
Run Code Online (Sandbox Code Playgroud)

然后做:

select PropertyCount 
  from PropertyCounters 
 where Property = @Property
Run Code Online (Sandbox Code Playgroud)

当表增长到成千上万的记录时,我合理地期望通过执行select count(*)会导致多少性能下降?

bob*_*nce 5

除了实际数据之外,还要保留单独的计数列是一种反规范化。有一些原因可能导致您需要这样做才能提高性能,但是除非真正需要,否则您不应该去那里。它使您的代码变得更加复杂,并且不一致的可能性也越来越大。

对于查询实际上只是的简单情况,SELECT COUNT(property) FROM table WHERE property=...没有理由进行非规范化。您可以通过在property列上添加索引来快速实现。