索引之explain分析使用詳情---一文足以解憂愁

一、什麼是索引

  • 索引是一種排好序的快速查找的數據結構,它幫助數據庫高效的查詢數據
  • 在數據之外,數據庫系統還維護着滿足特定查找算法的數據結構,這些數據結構以某種方式指向數據,這樣就可以在這些數據結構上實現高效的查找算法.這種數據結構,就是索引

在這裏插入圖片描述

  • 一般來說索引本身也很大,不可能全部存儲在內存中,因此往往以索引文件的形式存放在磁盤中
  • 我們平常所說的索引,如果沒有特別說明都是指BTree索引(平衡多路搜索樹).其中聚集索引,次要索引,覆蓋索引複合索引,前綴索引,唯一索引默認都是使用的BTree索引,統稱索引.除了BTree索引之後,還有哈希索引

二、索引優缺點

  • 優點:
  • 提高數據查詢的效率,降低數據庫的IO成本
  • 通過索引對數據進行排序,降低數據排序的成本,降低CPU的消耗
  • 缺點:
  • 索引本身也是一張表,該表保存了主鍵與索引字段,並指向實體表的記錄,所以索引列也要佔用空間
  • 雖然索引大大提高了查詢的速度,同時反向影響增刪改操作的效率,因爲表中數據變化之後,會導致索引內容不準,所以也需要更新索引表信息,增加了數據庫的工作量
  • 隨着業務的不斷變化,之前建立的索引可能不能滿足查詢需求,需要消耗我們的時間去更新索引

三、索引的分類

  • 單值索引: 一個索引只包含單列,一個表可以有多個單列索引
  • 唯一索引:索引列的值必須唯一,但是允許有空值
  • 複合索引: 一個索引可以同時包含多列

四、索引結構

1、BTree索引

在這裏插入圖片描述

  • 淺藍色: 磁盤塊

  • 深藍色: 數據項

  • 黃色: 數據的指針

  • 真實的數據僅在葉子節點中: 3, 5, 9, 10, 13, 15, 28, 29, 36, 60, 75, 79, 90,99

  • 查找過程: (假如要找29)

    1. 從樹根開始,即先把磁盤塊1中內容讀到內存中, 發生一次IO
    2. 確定29在(17,35)之間,鎖定磁盤塊1中的P2指針
    3. 根據P2指針,找到磁盤塊3, 讀取到內存中, 發生二次IO
    4. 29在(26,30)之間,鎖定磁盤塊3的P2指針
    5. 通過磁盤3的P2指針,將磁盤塊8的內容讀取到內存中, 發生第三次IO.
    6. 最終找到數據29,查詢結束,總共發生三次IO
  • 真實的情況:

    • 3層的BTree可以表示上百萬的數據,如果上百萬條數據,查找只需要三次IO,性能提高將是巨大的,如果沒有索引每次查找都要發生一次IO,那麼總共就需要百萬次的IO,顯然成本是非常高的

2、Hash索引
3、full-Text索引
4、R-Tree索引

五、索引的使用

1、創建索引的情況

  1. 主鍵約束默認建立唯一索引
  2. 頻繁作爲查詢條件的字段應該創建索引
  3. 多表查詢中與其它表進行關聯的字段,外鍵關係建立索引
  4. 單列索引/複合索引的選擇? 高併發下傾向於創建複合索引
  5. 查詢中經常用來排序的字段
  6. 查詢中經常用來統計或者分組字段

2、不創建索引的情況

  1. 頻繁更新的字段: 每次更新都會影響索引樹
  2. where條件查詢中用不到的字段
  3. 表記錄太少
  4. 經常增刪改的表: 更新了表,索引也得更新纔行
  5. 注意: 如果一張表中,重複的記錄非常多,爲它建立索引就沒有太大意義

3、索引創建語法

- 創建索引
create index 索引名稱 on 表名(列名...);

- 刪除索引
drop index 索引名稱 on 表名;

- 查看索引
show index from 表名;

六、性能分析

1、MySql Query Optimizer
mysql中有專門負責優化select語句的優化器模塊,主要功能:通過計算分析系統中收集到的統計信息,爲客戶端請求的Query提供mysql認爲最優的執行計劃

2、Mysql常見的瓶頸

  1. CPU飽和:CPU飽和的時候,一般發生在數據裝入內存或從磁盤上讀取數據的時候
  2. IO瓶頸: 磁盤IO瓶頸發生在裝入數據遠大於內存容量的時候
  3. 服務器硬件的性能瓶頸

七、執行計劃

使用explain關鍵字可以模擬優化器執行SQL查詢語句,從而知道MYSQL是如何處理SQL語句的.我們可以用執行計劃來分析查詢語句或者表結構的性能瓶頸
  1、作用

  1. 查看錶的讀取順序

  2. 查看數據庫讀取操作的操作類型

  3. 查看哪些索引有可能被用到

  4. 查看哪些索引真正被用到

  5. 查看錶之間的引用

  6. 查看錶中有多少行記錄被優化器查詢

2、語法

explain + sql語句

explain select * from tsmall;
+----+-------------+---------+------+---------------+------+---------+------+------+-------+
| id | select_type | table   | type | possible_keys | key  | key_len | ref  | rows | Extra |
+----+-------------+---------+------+---------------+------+---------+------+------+-------+
|  1 | SIMPLE      | product | ALL  | NULL          | NULL | NULL    | NULL |   16 |       |
+----+-------------+---------+------+---------------+------+---------+------+------+-------+

2.1 環境準備

create table t1(
  id int primary key,
  name varchar(20),
  col1 varchar(20),
  col2 varchar(20),
  col3 varchar(20)
);
create table t2(
  id int primary key,
  name varchar(20),
   col1 varchar(20),
   col2 varchar(20),
  col3 varchar(20)
);
create table t3(
  id int primary key,
  name varchar(20),
    col1 varchar(20),
   col2 varchar(20),
  col3 varchar(20)
);
insert into t1 values(1,'zs1','col1','col2','col3');
insert into t2 values(1,'zs2','col2','col2','col3');
insert into t3 values(1,'zs3','col3','col2','col3');

create index ind_t1_c1 on t1(col1);
create index ind_t2_c1 on t2(col1);
create index ind_t3_c1 on t3(col1);

create index ind_t1_c12 on t1(col1,col2);
create index ind_t2_c12 on t2(col1,col2);
create index ind_t3_c12 on t3(col1,col2);

2.2 id

  • select 查詢的序列號,包含一組數字,表示查詢中執行Select子句或操作表的順序
  • 三種情況:
  1. id值相同,執行順序由上而下
 explain select t2.* from t1,t2,t3 where t1.id = t2.id and t1.id= t3.id and t1.name = 'zs';

在這裏插入圖片描述

2.id值不同,id值越大優先級越高,越先被執行

explain select t2.* from t2 where id = (select id from t1 where id = (select t3.id from t3 where t3.name='zs3'));

在這裏插入圖片描述

3.id值有相同的也有不同的,如果id相同,從上往下執行,id值越大,優先級越高,越先執行

explain select t2.* from (select t3.id from t3 where t3.name='zs3') s1,t2 where s1.id = t2.id;

在這裏插入圖片描述
2.3 select_type

查詢類型,主要用於區別

  • SIMPLE : 簡單的select查詢,查詢中不包含子查詢或者UNION
  • List item
  • PRIMARY: 查詢中若包含複雜的子查詢,最外層的查詢則標記爲PRIMARY
  • SUBQUERY : 在SELECT或者WHERE列表中包含子查詢
  • DERIVED : 在from列表中包含子查詢被標記爲DRIVED衍生,MYSQL會遞歸執行這些子查詢,把結果放到臨時表中
  • UNION: 若第二個SELECT出現在union之後,則被標記爲UNION,若union包含在from子句的子查詢中,外層select被標記爲:derived
  • UNION RESULT: 從union表獲取結果的select
explain select col1,col2 from t1 union select col1,col2 from t2;

在這裏插入圖片描述
2.4 table
  顯示這一行的數據是和哪張表相關
2.5 type
訪問類型: all, index,range,ref,eq_ref, const,system,null

最好到最差依次是: system > const > eq_ref>ref >range > index > all , 最好能優化到range級別或則ref級別

  • system: 表中只有一行記錄(系統表), 這是const類型的特例, 基本上不會出現
  • const: 通過索引一次查詢就找到了,const用於比較primary key或者unique索引,因爲只匹配一行數據,所以很快,如將主鍵置於where列表中,mysql就會將該查詢轉換爲一個常量
 explain select * from (select * from t1 where id=1) s1;

在這裏插入圖片描述

  • eq_ref: 唯一性索引掃描, 對於每個索引鍵,表中只有一條記錄與之匹配, 常見於主鍵或者唯一索引掃描
  explain select * from t1,t2 where t1.id = t2.id;
  • ref : 非唯一性索引掃描,返回匹配某個單獨值的所有行,本質上也是一種索引訪問,它返回所有符合條件的行,然而它可能返回多個符合條件的行
   explain select * from t1 where col1='zs1';

在這裏插入圖片描述

  • range : 只檢索給定範圍的行, 使用一個索引來選擇行.key列顯示的是真正使用了哪個索引,一般就是在where條件中使用between,>,<,in等範圍的條件,這種在索引範圍內的掃描比全表掃描要好,因爲它只在某個範圍中掃描,不需要掃描全部的索引
explain select * from t1 where id between 1 and 10;

在這裏插入圖片描述

  • index : 掃描整個索引表, index 和all的區別爲index類型只遍歷索引樹. 這通常比all快,因爲索引文件通常比數據文件小,雖然index和all都是讀全表,但是index是從索引中讀取,而all是從硬盤中讀取數據
 explain select id from t1;

在這裏插入圖片描述

  • all : full table scan全表掃描 ,將遍歷全表以找到匹配的行
 explain select * from t1;
  • 注意: 開發中,我們得保證查詢至少達到range級別,最好能達到ref以上

2.6 possible_keys
  SQL查詢中可能用到的索引,但查詢的過程中不一定真正使用
2.7 key
查詢過程中真正使用的索引,如果爲null,則表示沒有使用索引

查詢中使用了覆蓋索引,則該索引僅出現在key列表中

 explain select t2.* from t1,t2,t3 where t1.col1 = ' ' and t1.id = t2.id and t1.id= t3.id;

在這裏插入圖片描述

explain select col1 from t1;

在這裏插入圖片描述
2.8 key_len
  索引中使用的字節數,可通過該列計算查詢中使用的索引的長度,在不損失精確度的情況下,長度越短越好, key_len顯示的值爲索引字段的最大可能長度,並非實際使用長度, 即key_len是根據表定義計算而得

 explain select * from t1 where col1='c1';

在這裏插入圖片描述

explain select * from t1 where col1='col1' and col2 = 'col2';

-- 注意: 爲了演示這個結果,我們刪除了c1上面的索引
alter table t1 drop index ind_t1_c1;
-- 執行完成之後,再次創建索引
create index ind_t1_c1 on t1(col1);

在這裏插入圖片描述

2.9 ref
  顯示索引的哪一列被使用了,如果可能的話,是一個常數.哪些列或者常量被用於查找索引列上的值

explain select * from t1,t2 where t1.col1 = t2.col1 and t1.col2 = 'col2';

在這裏插入圖片描述
2.10 rows
根據表統計信息及索引選用的情況,估算找出所需記錄要讀取的行數 (有多少行記錄被優化器讀取)

2.11 extra
包含其它一些非常重要的額外信息

  • Using filesort :說明mysql會對數據使用一個外部的索引排序,而不是按照表內的索引順序進行讀取,Mysql中無法利用索引完成的排序操作稱爲文件排序
 explain select col1 from t1 where col1='col1' order by col3;

在這裏插入圖片描述

-- 上面這條SQL語句出現了using filesort,但是我們去執行下面這條SQL語句的時候它,又不會出現using filesort
 explain select col1 from t1 where col1='col1' order by col2;

在這裏插入圖片描述

-- 如何優化第一條SQL語句 ? 
  create index ind_t1_c13 on t1(col1,col3);
  explain select col1 from t1 where col1='col1' order by col3;

在這裏插入圖片描述

  • Using temporary : 使用了臨時表保存中間結果,Mysql在對查詢結果排序時使用了臨時表,常見於order by
    和分組查詢group by
 explain select col1 from t1 where col1 >'col1' group by col1,col2;

在這裏插入圖片描述

explain select col1 from t1 where col1 >'col1' group by col1,col2;

在這裏插入圖片描述

  • Using index :
  • 查詢操作中使用了覆蓋索引(查詢的列和索引列一致),避免訪問了表的數據行,效率好
  • 如果同時出現了using where, 表明索引被用來執行索引鍵值的查找
  • 如果沒有同時出現using where, 表明索引用來讀取數據而非執行查找動作
  • 覆蓋索引: 查詢的列和索引列一致, 換句話說查詢的列要被所鍵的索引覆蓋,就是select中數據列只需從索引中就能讀取,不必讀取原來的數據行,MySql可以利用索引返回select列表中的字段,而不必根據索引再次讀取數據文件
explain select col2 from t1 where col1='col1';

在這裏插入圖片描述

explain select col2 from t1;

在這裏插入圖片描述

  • using where : 表明使用了where條件過濾
  • using join buffer : 表明使用了連接緩存, join次數太多了可能會出現
  • impossible where : where子句中的值總是false,不能用來獲取任何數據
 explain select * from t1 where col1='zs' and col1='ls';

在這裏插入圖片描述

  • select tables optimized away :
  • 在沒有group by 子句的情況下, 基於索引優化min/max操作或者對於MyISAM存儲引擎優化count(*)操作,不必等到執行階段再進行計算,查詢執行計劃生成階段即完成優化
  • distinct : 優化distinct操作,在找到第一個匹配的數據後即停止查找同樣的值的動作

3、小練習

 explain select a1.name,(select id from t3) a2
 from
    (select id,name from t1 where name='zs1') a1
union
    select name,id from t2;

在這裏插入圖片描述

id=4, select_type爲union, union後的select語句先被執行

id=3, 因爲(select id,name from t1 where name='zs1')被當作一張表處理,所以爲select_type 爲derived

id=2, select_type爲SUBQUERY,爲select後面的子查詢

id=1, 表示union中的第一個select, select_type爲primary表示該查詢爲外層查詢,table被標記爲<derived3>,表示結果來自衍生表

id=null,代表從union的臨時表中讀取行記錄, <union1,4>表示將id=1和id=4的結果進行union操作

4、索引優化

4.1 索引分析
單表

create table if not exists article(
  id int primary key auto_increment,
  author_id int not null,
  category_id int not null,
  views int not null,
  comments int not null,
  title varchar(255) not null,
  content text not null
);

insert into article values(null,1,1,1,1,'1','1');
insert into article values(null,2,2,2,2,'2','2');
insert into article values(null,1,1,3,3,'3','3');

select * from article;

-- 查詢category_id爲1且comments 大於 1 的所有記錄,顯示id,author_id,views

explain select  id,author_id,views  from  article
where category_id = 1
and comments > 1;

在這裏插入圖片描述

-- 查詢category_id爲1且comments 大於 1 的所有記錄,顯示id,author_id,views
-- 並且找出views查看次數最多的記錄
explain select  id,author_id,views from  article
where category_id = 1
and comments > 1
order by views desc limit 1;

在這裏插入圖片描述

-- 總結上面出現的情況:type=all,產生了全表掃描, 並且出現了Using filesort,使用了外部的索引排序,所以優化是必須的

-- 創建索引:
create index ind_article_ccv on article(category_id,comments,views);

--執行如下指令:
explain select  id,author_id,views from  article
where category_id = 1
and comments > 1
order by views desc limit 1;

在這裏插入圖片描述

創建索引之後type=range, 但是Using filesort 依然存在.

索引創建了,爲什麼在排序的時候沒有生效?
這是因爲先排序category_id, 如果遇到相同的category_id,則再排序comments, 如果遇到相同的comments則再排序views,
當comments字段在聯合索引處於中間位置時,
因爲comments>1條件是一個範圍值,所以type=range
mysql無法再利用索引對後面的views部分進行檢索,即range類型查詢字段後面的索引全都無效

綜上所述: 索引創建有問題

-- 刪除上面創建的索引:
drop index ind_article_ccv on article;
-- 重新創建索引: 
create index ind_art_cb on article(category_id,views);
-- 重新執行如下代碼

explain select  id,author_id,views from  article
where category_id = 1
and comments > 1
order by views desc limit 1;

在這裏插入圖片描述
兩張表
SQL準備

create table if not exists class(
    id int(10) primary key auto_increment,
      card int not null
);

create table  if not exists book(
    bookid int primary key auto_increment,
      card int not null
);

insert into class(card) values(floor(1+rand()*20));
insert into class(card) values(floor(1+rand()*20));
insert into class(card) values(floor(1+rand()*20));
insert into class(card) values(floor(1+rand()*20));
insert into class(card) values(floor(1+rand()*20));
insert into class(card) values(floor(1+rand()*20));
insert into class(card) values(floor(1+rand()*20));
insert into class(card) values(floor(1+rand()*20));
insert into class(card) values(floor(1+rand()*20));
insert into class(card) values(floor(1+rand()*20));

insert into book(card) values(floor(1+rand()*20));
insert into book(card) values(floor(1+rand()*20));
insert into book(card) values(floor(1+rand()*20));
insert into book(card) values(floor(1+rand()*20));
insert into book(card) values(floor(1+rand()*20));
insert into book(card) values(floor(1+rand()*20));
insert into book(card) values(floor(1+rand()*20));
insert into book(card) values(floor(1+rand()*20));
insert into book(card) values(floor(1+rand()*20));
insert into book(card) values(floor(1+rand()*20));
-- 下面開始分析
explain select * from class left join book on class.card = book.card;

+----+-------------+-------+------+---------------+------+---------+------+------+-------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+
|  1 | SIMPLE      | class | ALL  | NULL          | NULL | NULL    | NULL |   10 |       |
|  1 | SIMPLE      | book  | ALL  | NULL          | NULL | NULL    | NULL |   10 |       |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+

-- 結論: type 都有all
create index X on book(card);

-- 分析
explain select * from class left join book on class.card = book.card;
-- 我們可以看到第二行的type變爲了ref,rows也變小了,優化效果明顯

在這裏插入圖片描述

-- 這是由左連接特型決定的.left join條件用於確定如何從右表搜索行,左邊一定都有,所有右邊一定要建立索引 
 -- 我們再來看一個右外連接
 explain select * from class right join book on class.card = book.card;

在這裏插入圖片描述
三張表
SQL準備

create table if not exists phone(
    phoneid int primary key auto_increment,
      card int
);

insert into phone(card) values(floor(1+rand()*20));
insert into phone(card) values(floor(1+rand()*20));
insert into phone(card) values(floor(1+rand()*20));
insert into phone(card) values(floor(1+rand()*20));
insert into phone(card) values(floor(1+rand()*20));
insert into phone(card) values(floor(1+rand()*20));
insert into phone(card) values(floor(1+rand()*20));
insert into phone(card) values(floor(1+rand()*20));
insert into phone(card) values(floor(1+rand()*20));
insert into phone(card) values(floor(1+rand()*20));

-- 在沒有添加索引的情況下執行如下語句
explain select * from class left join book on class.card = book.card left join phone on book.card = phone.card;

-- 創建索引:
create index Y on book(card);
create index Z on phone(card);

在這裏插入圖片描述

-- 後2行的type都是ref且總rows數量大大降低了,效果不錯,因此索引最好是設置在需要經常查詢的字段中

-- 結論:
儘可能減少join語句中的循環總次數: 永遠用小結果集驅動大的結果集;
優先優化內層循環
保證join語句中被驅動表上的join條件字段已經創建過索引
當無法保證被驅動表的join條件字段是否有索引且內存資源充足的前提下,不要太吝惜JoinBuffer的設置

4.2 索引失效
建表語句

create table emp(
    empno int primary key auto_increment,
    ename varchar(24) not null default '' comment '姓名',
      age int not null default 0 comment '年齡',
      job varchar(20) not null default '' comment '職位',
      hiredate timestamp not null default current_timestamp comment '入職時間'
);

insert into emp(ename,age,job,hiredate) values('zs',22,'manager',now());
insert into emp(ename,age,job,hiredate) values('ls',23,'dev',now());
insert into emp(ename,age,job,hiredate) values('1000',24,'manager',now());
insert into emp(ename,age,job,hiredate) values('zss',22,'manager',now());
insert into emp(ename,age,job,hiredate) values('xzss',22,'manager',now());

select * from emp;

create index ind_emp_naj on emp(ename,age,job);
  1. 全值匹配我最愛: 查詢的條件列剛好和索引創建的列數量和順序相同

explain select * from emp where ename=‘zs’;
explain select * from emp where ename=‘zs’ and age=22;
explain select * from emp where ename=‘zs’ and age=22 and job=‘manager’;

  -- 有問題的sql
explain select * from emp where age=22 and job=‘manager’;
explain select * from emp where job=‘manager’;
– 沒有問題的sql
explain select * from emp where ename=‘zs’;

在這裏插入圖片描述
2. 最佳左前綴法則: 如果索引了多列,要遵循最左前綴法則. 查詢從索引的最左列開始並且不跳過索引中的列


explain select * from emp where ename=‘zs’ and job=‘manager’;

explain select * from emp where job=‘manager’;

explain select * from emp where ename=‘zs’;

3.不在索引上做任何操作(計算,函數,(自動/手動)類型轉換,這樣會導致索引失效而轉向全表掃描

explain select * from emp where left(ename,2)='zs';

4.存儲引擎不能使用索引中範圍條件右邊的列

– 使用到了索引
explain select * from emp where ename=‘zs’;
explain select * from emp where ename=‘zs’ and age=22;
explain select * from emp where ename=‘zs’ and age=22 and job=‘manager’;

explain select * from emp where ename=‘zs’ and age>22 and job=‘manager’;

5.儘量使用覆蓋索引(要查詢的列和索引中的列一致),避免使用select *

 explain select * from emp where ename='zs' and age=22 and job='manager';
    explain select ename,age,job from emp where ename='zs' and age=22 and job='manager';
  explain select ename,age,job from emp where ename='zs' and age>22 and job='manager';
   explain select ename,age,job from emp where ename='zs' and age=22;

6.mysql在使用不等於條件判斷的時候,索引會失效引發全表掃描

 explain select * from emp where ename='zs';
   explain select * from emp where ename != 'zs';

7.is null, is not null 索引會失效,無法使用索引

explain select * from emp where ename is null;
   explain select * from emp where ename is not null;

8.like以通配符開頭(‘%xxx…’)索引會失效,導致全表掃描


explain select * from emp where ename like%zs%;
explain select * from emp where ename like%zs’;
explain select * from emp where ename like ‘zs%;

--問題: 解決like ‘%xxx%’ 時索引失效的問題
explain select ename from emp where ename like%zs%;

explain select ename,age from emp where ename like%zs%;
explain select ename,age,job from emp where ename like%zs%;
explain select ename,age,job,hiredate from emp where ename like%zs%;

9.字符串不加單引號索引失效

explain select * from emp where ename=1000;
  explain select * from emp where ename='1000';

10.少用or,它會導致索引失效

explain select * from emp where ename='zs' or ename='ls';

11.小總結
在這裏插入圖片描述
4.3 面試題分析

create table test3(
    id int primary key auto_increment,
      c1 char(10),
      c2 char(10),
      c3 char(10),
      c4 char(10),
      c5 char(10)
);

insert into test3 values(null,'a1','a2','a3','a4','a5');
insert into test3 values(null,'b1','b2','b3','b4','b5');
insert into test3 values(null,'c1','c2','c3','c4','c5');
insert into test3 values(null,'d1','d2','d3','d4','d5');
insert into test3 values(null,'e1','e2','e3','e4','e5');

select * from test3;

-- 創建索引
create index ind_test3_c1234 on test3(c1,c2,c3,c4);
show index from test3;

explain select * from test3 where c1='a1';
explain select * from test3 where c1='a1' and c2='a2';
explain select * from test3 where c1='a1' and c2='a2' and c3='a3';
explain select * from test3 where c1='a1' and c2='a2' and c3='a3' and c4='a4';
explain select * from test3 where c1='a1' and c2='a2' and c3='a3' and c4='a4' and c5='a5';

-- 請執行如下問題SQL,分析會出現的問題
-- (1)
explain select * from test3 where c1='a1' and c2='a2' and c4='a4' and c3='a3' ;
-- (2)
explain select * from test3 where c4='a1' and c3='a2' and c2='a4' and c1='a3' ;
-- (3)
explain select * from test3 where c1='a1' and c2='a2' and c3>'a3' and c4='a4';
-- (4)
explain select * from test3 where c1='a1' and c2='a2' and c4>'a4' and c3='a3';
-- (5)
explain select * from test3 where c1='a1' and c2='a2' and c4='a4' order by c3; 
-- (6)
explain select * from test3 where c1='a1' and c2='a2' order by c3; 
-- (7)
explain select * from test3 where c1='a1' and c2='a2' order by c4; 
-- (8)
explain select * from test3 where c1='a1' and c5='a5' order by c2,c3; 
只用了c1這個字段索引,但是c2,c3用於排序,無filesort
explain select * from test3 where c1='a1' and c5='a5' order by c3,c2; 
只用了c1這個字段索引,但是由於c3,c2順序顛倒了,所以無法使用索引排序,出現filesort

-- (9)
explain select * from test3 where c1='a1' and c2='a2' order by c2,c3; 
-- (10)
explain select * from test3 where c1='a1' and c2='a2' and c5='a5' order by c2,c3; 
用到了c1,c2兩個字段索引,但是c2,c3用於排序,無filesort
explain select * from test3 where c1='a1' and c2='a2' and c5='a5' order by c3,c2; 
排序字段已經是一個常量,所以不會出現filesort

-- (11)
explain select * from test3 where c1='a1' and c4='c4' group by c2,c3;
用到了c1字段索引
explain select * from test3 where c1='a1' and c4='c4' group by c3,c2;
索引字段順序不正確,出現了Using temporary; Using filesort

建議

  • 對於單列索引,儘量選擇針對當前查詢過濾性更好的索引
  • 在選擇複合索引的時候,當前查詢中過濾性最好的字段在索引字段順序中,位置越靠前越好
  • 在創建複合索引的時候,儘量選擇能夠包含查詢中where子句中更多的字段
  • 儘可能通過分析統計信息和調整查詢的寫法來達到選擇合適索引的目的

4.4 in和exists
優化規則: 小表驅動大表,即小的數據集驅動大的數據集

-- 當A的數據集大於B的數據集時, in 優於 exists
select * from A where id in (select id from B);
等價於:
    for select id from B
        for select * from A where A.id = B.id;

-- 當A的數據集小於B的數據集時, exists優於in
select * from A where exists(select 1 from B where B.id = A.id);
等價於:
    for select * from A
        for select * from B where B.id = A.id

4.5 Order by 排序優化

  1. order by 子句,儘量使用index方式排序,避免使用Filesort方式排序
 select * from emp order by age
   select * from emp order by age,birth
    select * from emp order by birth,age
    select * from emp order by age asc,birth desc;

儘可能再索引列上完成排序操作,遵照索引建的最佳左前綴

  1. 如果不在索引列上,filesort算法:雙路排序,單路排序

  2. 雙路排序: mysql4.1之前使用的雙路排序,字面意思就是掃描兩次磁盤,從而得到最終的數據,讀取行指針和order by列,對它們進行排序,然後掃描已經排序好的列表,按照列表中的值重新從列表中讀取對應的數據輸出.
    從磁盤取排序字段,在buffer進行排序,再從磁盤取其它字段

  3. 單路排序:從磁盤讀取查詢需要的所有列,按照orderby列在buffer對它們進行排序,然後掃描排序後的列表進行輸出,它的效率更快一些,避免了第二次讀取數據.並且把隨機IO變成了順序IO,但是它會使用更多的空間,因爲它把每一行都保存到內存中

  4. 結論:

    1. 單路排序,優於雙路排序

    2. 在sort_buffer中,單路要比雙路佔用更多的空間,因爲單路是把所有的字段都取出來,有可能導致取出的數據總大小超出了sort_buffer的容量,導致每次只能取sort_buffer容量大小的數據,進行排序(創建tmp,多路合併),排完再取sort_buffer容量大小,再排…從而導致了多次IO.(本來想節省一次IO操作,反而導致了大量的IO操作,得不償失)

  5. 優化策略

  6. 增大sort_buffer_size參數設置

  7. 增大max_length_for_sort_data參數設置

  8. why

    1. order by時,select * 時一個大忌,只查詢需要的字段,這點非常重要.

      1. 當查詢的字段大小總和小於max_length_for_sort_data而且排序字段不是TEXT|BLOB類型時,會用單路排序,否則會用多路排序

      2. 兩種算法的數據都有可能超過sort_buffer的容量,超出之後,會創建tmp文件進行合併排序,導致多次IO,但是用單路排序算法的風險會更大一些,所以要提高sort_buffer_size

    2. 嘗試調高sort_buffer_size:不管使用哪種算法,提高這個參數都會提高效率,當然,要根據系統的能力去調高,因爲這個參數是針對每個進程的

    3. 嘗試調高max_length_for_sort_data:調高這個參數,會增加使用單路算法的概率,但是如果設置太高,數據總容量超出sort_buffer_size的概率就增大,明顯症狀是高的磁盤IO活動和低的處理器使用率

  9. 總結

mysql有兩種排序方式: 文件排序和掃描有序索引排序
mysql能爲排序和查詢使用相同的索引

index abc(a,b,c)
order by 能使用最左前綴
order by a
order by 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=const order by a,d /*d不是索引*/
where a in() order by b,c /*對於排序來說,in 相當於是範圍查詢*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章