好像在网上见过说如果用in的话就会引起表扫描
做了个实验:if object_id('temp') is not null
drop table temp
create table temp(id int identity(1,1) primary key,[name] varchar(50))
go
insert into temp values('test')
go 100--下面的查找全部用了聚集索引扫描
select * from temp where id=1 select * from temp where id=1 or id=2select * from temp where id in(1,2)select * from temp where id=1 union select * from temp where id=2select * from temp where id not in(1,2)select * from temp where id in(select id from temp)
那什么情况下用in不会聚集索引扫描?
做了个实验:if object_id('temp') is not null
drop table temp
create table temp(id int identity(1,1) primary key,[name] varchar(50))
go
insert into temp values('test')
go 100--下面的查找全部用了聚集索引扫描
select * from temp where id=1 select * from temp where id=1 or id=2select * from temp where id in(1,2)select * from temp where id=1 union select * from temp where id=2select * from temp where id not in(1,2)select * from temp where id in(select id from temp)
那什么情况下用in不会聚集索引扫描?
取决于所查数据占总数据的一个比例,比例越小,使用索引查找的机率越大,反之,使用索引扫描机率大。
所以不能单纯的定论in 或 not in 是否使用索引。
那么
select * from temp where id in(1,2)
这个语句是不是所查的数据与总数据的比例很小?是不是就是用表扫描的几率更大?
但是结果它使用的还是聚集索引扫描?
确定下是聚集索引扫描还是聚集索引查找?clustered index seek 和 clustered index scan 是不同的。
我就是想知道在什么情况下会不是聚集索引扫描,以便以后在写sql的时候注意
能否给举个例子?
那个显示的是clustered index seek
知道了clustered index seek 和 clustered index scan的区别
sacn就是整个表扫描
所以以下
select * from temp where id=1 select * from temp where id=1 or id=2select * from temp where id in(1,2)select * from temp where id=1 union select * from temp where id=2select * from temp where id not in(1,2)select * from temp where id in(select id from temp)
除了最后一个以外全都是索引查找
最后一个是索引扫描
clustered index scan 说明没有有效利用索引,而使用了全扫。
http://blog.csdn.net/no_mIss/archive/2006/10/09/1327771.aspx