mysql查詢優化之explain的深入解析
首先執行如下的 sql 語句:
想要查詢 category_id 為 1 且 comments 大於 1 的情況下,views 最多的 article_id。create
table
ifnot
exists
`article` (`id`
int(10) unsigned not
null auto_increment,
`author_id`
int(10) unsigned not
null,
`category_id`
int(10) unsigned not
null,
`views`
int(10) unsigned not
null,
`comments`
int(10) unsigned not
null,
`title` varbinary(255) not
null,
`content` text not
null,
primary
key (`id`)
);insert
into
`article`
(`author_id`, `category_id`, `views`, `comments`, `title`, `content`) values
(1, 1, 1, 1, '1', '1'),
(2, 2, 2, 2, '2', '2'),
(1, 1, 3, 3, '3', '3');
語句如下(在傳統的查詢語句前加上 explain 關鍵字):
給出如下的查詢結果:explain
select author_id
from
`article`
where category_id = 1
and comments > 1
order
by views desc
limit 1;
mysql 查詢優化器有幾個目標,但是其中最主要的目標是盡可能地使用索引,並且使用最嚴格的索引來消除盡可能多的資料行。id:
1select_type: ******
table: article
type: all
possible_keys: null
key: null
key_len: null
ref: null
rows:
3extra: using where; using filesort
1 row in
set (0.00
sec)
table:輸出行所引用的表
extra:中出現以下 2 項意味著 mysql 根本不能使用索引,效率會受到重大影響。應盡可能對此進行優化。using temporary:表示 mysql 在對查詢結果排序時使用臨時表。常見於排序 order by 和分組查詢 group by。
如果 explain 的輸出結果中,type 對應的是 all,extra 還出現了 using filesort,都意味著 sql 語句雖然能夠工作,但其實是最壞的,並沒有合理使用的 sql 查詢語句。
新增 index 索引之後,再次呼叫 explain 語句,可以看到,type 變成了range,這是可以忍受的。但是 extra 裡使用 using filesort 仍是無法接受的。也即並未使用上面建立的索引。這是因為按照 btree 索引的工作原理,先排序 category_id,如果遇到相同的 category_id 則再排序 comments,如果遇到相同的 comments 則再排序 views。當 comments 欄位在聯合索引裡處於中間位置時,因comments > 1 條件是乙個範圍值,mysql 無法利用索引再對後面的 views 部分進行檢索,即 range 型別查詢字段後面的索引無效。alter
table
`article`
add index x ( `category_id` , `comments`, `views` );
drop index x on article;
alter
table
`article`
add index y ( `category_id` , `views` ) ;
mysql效能優化之EXPLAIN
mysql效能分析及explain用法的知識是本文我們主要要介紹的內容,接下來就讓我們通過一些實際的例子來介紹這一過程,希望能夠對您有所幫助。1.使用explain語句去檢視分析結果 如explain select from test1 where id 1 會出現 id selecttype ta...
MySQL效能優化之explain
在日常工作中,我們會有時會開慢查詢去記錄一些執行時間比較久的sql語句,找出這些sql語句並不意味著完事了,些時我們常常用到explain這個命令來檢視乙個這些sql語句的執行計畫,檢視該sql語句有沒有使用上索引,有沒有做全表掃瞄,這都可以通過explain命令來檢視。所以我們深入了解mysql的...
mysql優化之EXPLAIN語句
explaintbl name 或 explain extended selectselect options explain語句可以用作describe的乙個同義詞,或獲得關於mysql如何執行select語句的資訊 借助於這個語句,我們也可以分析出,索引對於查詢的作用,以及何時應該可以資料表新增...