-- auto-generated definition
create table test
(
id int not null
primary key,
name char(30) not null,
local char(30) not null,
age int null
);
create index test_name_local_age_index
on test (name, local, age);
explain参数参考
ref:只会读取匹配的行,当查询的列是一个索引的最左前缀或者是一个普通索引(不是主键索引或唯一索引)会使用 ref
。即仅仅会查询几行。
index: 连接类型与 all
相同,除了是扫描索引树外。主要有如下两种方式:
- 如果查询的索引时覆盖索引,并且满足要从该表中查询的数据需求,则仅扫描索引树。在这种情况下,
Extra
列为Using index
。索引扫描仅仅会比 ALL 快,因为索引树通常小于整个表。 - 通过对索引的读取进行全表扫描,以按照索引顺序查找数据行,
Using index
不会出现在Extra
列。
explain select * from test where name = '1' and local = '1' and age = 1;
符合最左匹配原则,通过explain执行结果可以看到type = ref,key使用了联合索引
explain select * from test where name = '1' and age = 1 and local = '1';
可以看到跟第一个执行结果一致,这是因为SQL语句经过优化器优化之后,依然符合最左匹配原则
explain select * from test where local = '1' and age = 1;
虽然不符合最左匹配原则,但是发现还是使用了索引,这是因为建表语句一共四个字段,除了主键其他的字段组成联合索引,就意味着表里面的所有数据都能在联合索引里面找到,如果增加一个字段重新执行就会发现全表扫描了。
-- auto-generated definition
create table test
(
id int not null
primary key,
name char(30) not null,
local char(30) not null,
age int null,
e_mail varchar(50) null
);
create index test_name_local_age_index
on test (name, local, age);
可以看到type = ALL,extra信息里面没有using index