前提
表定义、数据插入、索引定义
-- 表定义,及数据插入
create table op_param_sniffing (
id bigint IDENTITY(1,1) not null,
product_id varchar(100) not null,
product_name varchar(100) not null
)
declare @id int;
set @id = 1;
while @id < 14
begin
insert into op_param_sniffing(product_id, product_name) values('100', '商品100')
set @id = @id + 1
end
while @id < 100
begin
insert into op_param_sniffing(product_id, product_name) values('200', '商品200')
set @id = @id + 1
end
while @id < 1000
begin
insert into op_param_sniffing(product_id, product_name) values('300', '商品300')
set @id = @id + 1
end
-- 索引
create index idx_op_param_sniffing_product_id on op_param_sniffing(product_id)
试验
1)
select * from op_param_sniffing where product_id = ‘100’
select product_id from op_param_sniffing where product_id = ‘100’
这两个sql的执行计划分别是:
可以看到select*时并不会选择索引,因为索引里只有product_id, 其它返回列还需要回表查询,优化器应该是认为还不如全表扫描吧。
2)我们加大数据量到10w
declare @id int;
set @id = 1000;
while @id < 100001
begin
insert into op_param_sniffing(product_id, product_name) values('300', '商品300')
set @id = @id + 1
end
再来看实际的执行计划:
我们可以看到select*开始的sql也走索引了!这是因为在10w行记录里只有十几行目标数据,既然回表查询也会比全表扫描快!