不错呦!smile@林凯西,确保“准备文件”中的几个文件都有安装,S...您好,看了您这篇帖子觉得很有帮助。但是有个问题想请...我的修改过了怎么还被恶意注册呢 @jjjjiiii 用PJ快9年了,主要是A...PJ3啊,貌似很少有人用PJ了,现在不是WP就是z...@332347365,我当时接入时错误码没有-10...楼主,ChkValue值应为-103是什么意思呢?...大哥 你最近能看到我发的信息,请跟我联系,我有个制...
SQL Server查询数据三种方式Table Scan/Index Seek/Index Scan小结
编辑:dnawo 日期:2012-12-16
当向SQL Server查询数据时,有三种数据查询方式可供选择:Table Scan、Index Seek和Index Scan,下边我们说说它们的概念,使用场合, 以及优先级,所有测试使用数据库版本SQL Server 2008。
1.概念
Table Scan:全表扫描,没有用到索引;
Index Seek:索引查找,有用到索引,根据聚集索引和非聚集索引分为Clustered Index Seek和NonClustered Index Seek;
Index Scan:索引扫描,有用到索引,效率比Table Scan高,但低于Index Seek。也分为Clustered Index Scan和NonClustered Index Scan;
2.使用场合
2.1 Table Scan
一般只有当表没有创建索引时才会用到Index Scan,否则SQL Server只使用Index Seek和Index Scan。下边我们创建一个表test(不创建索引):
执行查询并查看执行计划:

2.2 Index Seek
接下来我们为表test创建一个聚集索引和一个非聚集索引,并添加1W条数据:
执行查询并查看执行计划:

说明:当数据量比较少时,所有查询可能都用Clustered Index Seek。
2.3 Index Scan
执行查询并查看执行计划:

三、什么时候会用到Index Seek?
显然,Index Seek查询效率最高,我们应该在查询中尽量用Index Seek,那什么时候会用到Index Seek呢?我们再看两个查询的执行计划:

综合2.2和2.3的例子,当满足以下条件时会用到Index Seek:
·索引全部字段包含在where子句中;
·复合索引部分字段包含在where子句中且是索引前几个字段;
四、优先级
根据2.3和第3节的例子,不难得出优先级Table Scan/Index Seek/Index Scan顺序如下(从高到低):
引用内容
1.概念
Table Scan:全表扫描,没有用到索引;
Index Seek:索引查找,有用到索引,根据聚集索引和非聚集索引分为Clustered Index Seek和NonClustered Index Seek;
Index Scan:索引扫描,有用到索引,效率比Table Scan高,但低于Index Seek。也分为Clustered Index Scan和NonClustered Index Scan;
2.使用场合
2.1 Table Scan
一般只有当表没有创建索引时才会用到Index Scan,否则SQL Server只使用Index Seek和Index Scan。下边我们创建一个表test(不创建索引):
复制内容到剪贴板
程序代码

create table test
(
a int,
b int,
c int,
d int
)
(
a int,
b int,
c int,
d int
)
执行查询并查看执行计划:
复制内容到剪贴板
程序代码

select * from test

2.2 Index Seek
接下来我们为表test创建一个聚集索引和一个非聚集索引,并添加1W条数据:
复制内容到剪贴板
程序代码

create clustered index pk_a on test(a)
create index ix_b_c on test(b,c)
--1W
declare @i int
set @i=1
while(@i<=10000) begin
insert into test(a,b,c,d) select @i,@i,@i,@i
set @i=@i+1
end
create index ix_b_c on test(b,c)
--1W
declare @i int
set @i=1
while(@i<=10000) begin
insert into test(a,b,c,d) select @i,@i,@i,@i
set @i=@i+1
end
执行查询并查看执行计划:
复制内容到剪贴板
程序代码

select * from test where a=1
select * from test where b=1 and c=1
select * from test where b=1 and c=1

说明:当数据量比较少时,所有查询可能都用Clustered Index Seek。
2.3 Index Scan
执行查询并查看执行计划:
复制内容到剪贴板
程序代码

select * from test where d=1
select * from test where c=1
select * from test where c=1

三、什么时候会用到Index Seek?
显然,Index Seek查询效率最高,我们应该在查询中尽量用Index Seek,那什么时候会用到Index Seek呢?我们再看两个查询的执行计划:
复制内容到剪贴板
程序代码

select * from test where a=1 and b=1 and c=1
select * from test where b=1 and c=1 and d=1
select * from test where b=1 and c=1 and d=1

综合2.2和2.3的例子,当满足以下条件时会用到Index Seek:
·索引全部字段包含在where子句中;
·复合索引部分字段包含在where子句中且是索引前几个字段;
四、优先级
根据2.3和第3节的例子,不难得出优先级Table Scan/Index Seek/Index Scan顺序如下(从高到低):

Clustered Index Seek>NonClustered Index Seek>NonClustered Index Scan>Clustered Index Scan>Table Scan
评论: 0 | 引用: 0 | 查看次数: 5757
发表评论
请登录后再发表评论!