尽量使用index方式排序,避免使用filesort方式排序
create table tblA(
#id int primary key not null auto_increment,
age int,
birth TIMESTAMP not null
);
insert into tblA(age,birth) values(22,now());
insert into tblA(age,birth) values(22,now());
insert into tblA(age,birth) values(22,now());
-- 在age和birth上建立索引
create index idx_A_ageBirth on tblA(age,birth);
select * from tblA;
-- type为index类型的
EXPLAIN SELECT * FROM tblA WHERE age>10 ORDER BY age;
EXPLAIN SELECT * FROM tblA WHERE age>10 ORDER BY age,birth;
-- 这个产生了filesort了,因为带头大哥age不在了
EXPLAIN SELECT * FROM tblA WHERE age>10 ORDER BY birth;
EXPLAIN SELECT * FROM tblA WHERE age>10 ORDER BY birth,age;
EXPLAIN SELECT * FROM tblA ORDER BY birth;
EXPLAIN SELECT * FROM tblA WHERE birth>'2018-02-23 00:00:00' ORDER BY birth;
-- 这个没有filesort,age就是大哥
EXPLAIN SELECT * FROM tblA WHERE birth>'2018-02-23 00:00:00' ORDER BY age;
-- 这个有filesort,索引建立默认是升序
EXPLAIN SELECT * FROM tblA ORDER BY age ASC,birth DESC;
mysql支持两种方式的排序,filesort和index,index效率高,它指mysql扫描索引本身完成排序。filesort方式效率低
order by满足两种情况,会使用index方式排序
提高order by的速度
mysql两种排序方式:文件排序或扫描有序索引排序
mysql能为排序与查询使用相同的索引
key a_b_c(a,b,c)
order by能使用索引最左前缀
order by a
order by a,b
order by a,b,c
order by a desc,b desc,c desc #这个同时都为降序所以也可以
如果where使用索引的最左前缀定义为常量,则order by能使用索引
where a=const order by b,c
where a=const and b=const order by c
where a=const order by b,c
where a=const and b>const order by b,c
不能使用索引进行排序
order by a asc,b desc,c desc #排序不一致,有升序有降序
where g=const order by b,c #丢失a索引,没有带头大哥
where a=const order by c #丢失b索引
where a in(...) order by b,c #对于排序来说,多个相等条件也是范围查询