0

我发现“count( ) over()”会比“select count( ) from table”快得多。

例如

使用 count( *) 结束

with CTE as( select col_A,col_B,totalNumber=count(*) over() from table1 where conditions..) select totalNumber from CTE

使用 select count( *) from ( 或者也使用 count(1) )

select count(*) from table1 where conditions..

在我对SQL Server 2K5的本地测试中,如果搜索条件复杂且返回的行很大,则count( ) over* 将快 4 倍。

但是为什么 count(**) over 执行得这么快呢?

谢谢你的建议。

万斯

更新

我认为真的错过了一些细节:

实际上,我使用“准备语句” sql 进行测试,例如:

exec sp_executesql N'SELECT count(*) FROM tableA WHERE (aaa in(@P0)) AND (bbb like @P1)', N'@P0 nvarchar(4000),@P1 nvarchar(4000)',N'XXXXXXX-XXXX-XXX',N'%AAA%'

Execution Plan says "HashMatch" cost 61%, others is "index seek". And the execution time will be 1484ms and logical reads around 4000.

SELECT count(*) FROM tableA WHERE (aaa in('XXXXXXX-XXXX-XXX')) AND (bbb like '%AAA%') Execution plan says "clustered index seek" cost 98%. And the execution time is 46ms and logical reads will be 8000.

如果将第一个 sql 更改为:

exec sp_executesql N'with CTE as( SELECT total=count(*) over () FROM tableA WHERE (aaa in(@P0)) AND (bbb like @P1)) select top 1total from cte', N'@P0 nvarchar(4000),@P1 nvarchar(4000)',N'XXXXXXX-XXXX-XXX',N'%AAA%' Execution plan says "clustered index seek 58%', no "hashmatch join" occurs.

And the execution time is 15ms and logical reads is: 8404.

那么,“哈希匹配连接”是否对性能有很大的开销?

4

0 回答 0