mysql 索引优化查询测试
**************************
测试表
字段:id、name、age、distance
插入10万条数据
drop procedure if exists hh;
delimiter //
create procedure hh()
begin
declare i int default 1;
declare count int default 100000;
while i<=count do
insert into test(id,name,age,distance) values(i,concat('gtlx ',i),(i%20)+10,round(rand()*1000)+100);
set i=i+1;
end while;
end //
delimiter ;
call hh();
**************************
like 操作符
在name、age列上建立复合索引 name_age:name在前,age在后
select * from where name like "gtlx 2%";
说明:该语句使用了索引name_age
select * from where name like "gtlx%";
说明:由于匹配的列过多,没有使用索引
select * from where name like "%gtlx";
说明:该select语句没有使用索引
**************************
否定操作:not、!=
select * from test where name ="gtlx";使用索引
select * from test where not name="gtlx";not否定操作不使用索引
select * from test where name!="gtlx";否定操作!= 不使用索引
**************************
索引列上使用函数、计算表达式不使用索引
select * from test where age>20;匹配数据过多,不使用索引
select * from test where (age-2)>20;索引列上使用计算表达式,不使用索引
select * from test where round(age)>20;索引上使用函数,不使用索引
**************************
or 操作符:两边索引列都有索引使用索引
查询语句:select * from test where name="gtlx" or age>30;
只在age列上建立索引:不使用索引
分别在name、age列上建立索引:使用索引
在name、age列上建立复合索引:不使用索引
**************************
and 操作符
查询语句:
select * from where name="gtlx" and age>30;使用索引
select * from where age>30 and name="gtlx";使用索引
说明:and 索引列的顺序不影响索引的使用