2012-04-20 17 views
1

我有一張表,想檢查是否存在滿足某些簡單條件的任何記錄。 我想知道,這將加快工作速度:sql,存在或計數

if (select count(*) from ... where ...) > 0

if exists (select top (1) from ... where ...)

+4

存在返回結果只要它發現與匹配where-clause的記錄,而計數需要掃描整個表以確定計數。所以存在更快 – rt2800 2012-04-20 12:34:12

+0

rt2800,寫作答案,我會接受它))) – superM 2012-04-20 12:35:32

+4

http://sqlblog.com/blogs/andrew_kelly/archive/2007/12/15/exists-vs-count-the- battle-never-ends.aspx – ken2k 2012-04-20 12:39:19

回答

5

存在的回報,一旦發現紀錄,同時計數需要掃描整個表以確定計數where子句匹配的結果。因此存在更快

3
if exists (select 1 from ... where ...) 

(假設你對where列索引...)