必要知识:
EXPlAIN :模拟优化器执行sql查询语句,从而知道mysql是如何处理你的sql语句,分析你的查询语句或是表结构的性能瓶颈。
使用方式:Explain + Sql语句
explain select * from tbl_user;
create table sql:
create table test1
(
id int primary key auto_increment,
firstName varchar(20) not null,
lastName varchar(20) not null,
age int not null,
idNumber varchar(20) not null
);
未创建索引 select sql:
explain select *
from test1
where firstName = 'a'
and lastName = 'b'
and age = 1;
result:
主要字段:
type:all
创建索引:
create index idx_firstName_lastName_age on test1 (firstName, lastName, age)
再次查询:
explain select *
from test1
where firstName = 'a'
and lastName = 'b'
and age = 1;
result:
主要字段:
type:ref
possible_keys: idx_firstName_lastName_age
key:idx_firstName_lastName_age
key_len:128
reft:const,const,const
将firstName去掉(头部索引):
explain
select *
from test1
where lastName = 'b'
and age = 1;
result(索引失效):
主要字段
type: all
总结:创建的联合索引失去第一个索引导致索引失效
将lastName去掉(中间索引):
explain
select *
from test1 where firstName='1' and age=1;
主要字段:
type:ref
possible_keys:idx_firstName_lastName_age
key:idx_firstName_lastName_age
key_len:62
总结:未使用全部索引 key_len 精度丢失
explain select lastName,age from test1 where lastName='' and age=1;
explain select * from test1 where firstName='1';
explain select * from test1 where length(firstName)='1';
explain select * from test1 where firstName=1;
explain select * from test1 where firstName+''='1';
result:
需要修改索引:
drop index idx_firstName_lastName_age on test1;
create index idx_firstName_lastName_age on test1 (firstName, age, lastName);
explain select * from test1 where firstName='1'; explain select * from test1 where firstName='1' and age=100; explain select * from test1 where firstName='1' and age=100 and lastName='1'; explain select * from test1 where firstName='1' and age<100 and lastName='1';
结论:
select * from test1 where firstName='1' and age=100; 与 explain select * from test1 where firstName='1' and age<100 and lastName='1'; 使用了同样的key_len精度 而后面的 lastName 并没有用到。
explain select * from test1 where firstName='1' and age=1 and lastName='1'; explain select * from test1 where firstName<>'1' and age=1 and lastName='1';
explain select * from test1 where firstName='1' and lastName='1' and age=1; explain select * from test1 where firstName ='1' or lastName='1' and age=1;
explain select * from test1 where firstName='1'; explain select * from test1 where firstName like '%1';
explain select * from test1 where firstName like '1%';
解决方案:覆盖索引
explain select firstName from test1 where firstName like '%1';