Using filesort表示在索引以外,須要額外進行外部的排序動做。致使該問題的緣由通常和order by有者直接關係,通常能夠經過合適的索引來減小或者避免。java
1.首先建表和索引(如下使用的sql版本是5.5.54)mysql
/*課程表*/
create table course(
id int primary key auto_increment,/* 主鍵自增*/
title varchar(50) not null,/* 標題*/
category_id int not null,/* 屬於哪一個類目*/
school_id int not null,/* 屬於哪一個學校*/
buy_times int not null,/* 購買次數*/
browse_times int not null/* 瀏覽次數*/
);
insert into course(title,category_id,school_id,buy_times,browse_times) values('java課程',1,1,800,8680);
insert into course(title,category_id,school_id,buy_times,browse_times) values('android課程',2,1,400,8030);
insert into course(title,category_id,school_id,buy_times,browse_times) values('mysql課程',3,2,200,2902);
insert into course(title,category_id,school_id,buy_times,browse_times) values('oracle課程',2,2,100,6710);
insert into course(title,category_id,school_id,buy_times,browse_times) values('C#課程',1,3,620,2890);
insert into course(title,category_id,school_id,buy_times,browse_times) values('PS課程',4,4,210,4300);
insert into course(title,category_id,school_id,buy_times,browse_times) values('CAD課程',5,1,403,6080);
/*在category_id和buy_times上創建組合索引*/
create index idx_cate_buy on course(category_id,buy_times);
複製代碼
2.order by 和 group by 會產生 using filesort的有哪些?android
(1)explain select id from course where category_id>1 order by category_id;sql
根據最左前綴原則,order by後面的的category_id會用到組合索引oracle
(2)explain select id from course where category_id>1 order by category_id,buy_times;spa
根據最左前綴原則,order by後面的的category_id buy_times會用到組合索引,由於索引就是這兩個字段code
(3)explain select id from course where category_id>1 order by buy_times;cdn
根據最左前綴原則,order by後面的字段是缺乏了最左邊的category_id,因此會產生 using filesort排序
(4)explain select id from course where category_id>1 order by buy_times,category_id;索引
order by後面的字段順序不符合組合索引中的順序,因此order by後面的不會走索引,即會產生using filesort
(5)explain select id from course order by category_id;
根據最左前綴原則,order by後面存在索引中的最左列,因此會用到索引
(6)explain select id from course order by buy_times;
根據最左前綴原則,order by後面的字段 沒有索引中的最左列的字段,因此不會走索引,會產生using filesort
(7)explain select id from course where buy_times > 1 order by buy_times;
根據最左前綴原則,order by後面的字段 沒有索引中的最左列的字段,因此不會走索引,會產生using fillesort
(8)explain select id from course where buy_times > 1 order by category_id;
根據最左前綴原則,order by後面的字段存在於索引中最左列,因此會走索引
(9)explain select id from course order by buy_times desc,category_id asc;
根據最最左前綴原則,order by後面的字段順序和索引中的不符合,則會產生using filesort
(10)explain select id from course order by category_id desc,buy_times asc;
這一條雖然order by後面的字段和索引中字段順序相同,可是一個是降序,一個是升序,因此也會產生using filesort,同時升序和同時降序就不會產生using filesort了
總結:終上所述,(3)(4)(6)(7)(9)(10)都會產生using filesort.