索引如何适用于以下查询?

时间:2016-06-07 14:35:35

标签: sql-server

我用主键创建了下表:

create table test2
(id int primary key,name varchar(20))  

insert into test2 values
(1,'mahesh'),(2,'ram'),(3,'sham')  

然后在其上创建了非聚集索引。

 create nonclustered index ind_non_name on test2(name)

当我写下面的查询时,它总是会在查询执行计划中使用非聚簇索引。

select COUNT(*) from test2  
select id from test2   
select * from test2   

即使我们在桌面上有聚集索引,你能否帮我理解它为什么总是使用非聚集索引?

提前致谢。

3 个答案:

答案 0 :(得分:1)

基本上,当您在名称上创建非聚集索引时,索引实际上包含name和id,因此它包含所有表本身。 如果你添加另一个这样的字段:

create table test4
(id int primary key clustered,name varchar(20), name2 varchar(20))  

insert into test4 values
(1,'mahesh','mahesh'),(2,'ram','mahesh'),(3,'sham','mahesh')  

 create nonclustered index ind_non_name on test4(name)

您将看到一些查询将开始使用聚集索引。

答案 1 :(得分:0)

在您的情况下,索引几乎是一样的,因为聚簇索引也包含数据,您的聚簇索引是id, name而非聚簇索引包含聚簇键,因此非聚簇索引是{{ 1}}。

您没有任何搜索条件,因此无论使用哪个索引,都必须完全扫描它,为什么它实际上应该使用聚簇索引?

如果你在表中添加第三个字段,那么至少name, id将使用聚集索引。

答案 2 :(得分:0)

您将主键与群集密钥混淆。他们不一样。您需要显式创建群集密钥。

要在create语句中的主键上创建聚类键:

create table test2
(id int ,name varchar(20)
 constraint PK_ID_test2 primary key clustered(id))  

将聚类键添加到您已经拥有的内容中:

ALTER TABLE test2   
ADD CONSTRAINT PK_ID_test2 primary key clustered(id)
相关问题