1.基礎(chǔ)的含義解釋
id:select查詢的序列號(hào)
select_type:select查詢的類型,主要是區(qū)別普通查詢和聯(lián)合查詢、子查詢之類的復(fù)雜查詢。
table:輸出的行所引用的表。
type:聯(lián)合查詢所使用的類型。type顯示的是訪問類型,是較為重要的一個(gè)指標(biāo),結(jié)果值從好到壞依次是:
system > const > eq_ref > ref > fulltext > ref_or_null > index_merge > unique_subquery > index_subquery > range > index > ALL
一般來說,得保證查詢至少達(dá)到range級(jí)別,最好能達(dá)到ref。possible_keys:指出MySQL能使用哪個(gè)索引在該表中找到行。如果是空的,沒有相關(guān)的索引。這時(shí)要提高性能,可通過檢驗(yàn)WHERE子句,看是否引用某些字段,或者檢查字段不是適合索引。
key:顯示MySQL實(shí)際決定使用的鍵。如果沒有索引被選擇,鍵是NULL。
key_len:顯示MySQL決定使用的鍵長度。如果鍵是NULL,長度就是NULL。文檔提示特別注意這個(gè)值可以得出一個(gè)多重主鍵里mysql實(shí)際使用了哪一部分。
ref:顯示哪個(gè)字段或常數(shù)與key一起被使用。
rows:這個(gè)數(shù)表示mysql要遍歷多少數(shù)據(jù)才能找到,在innodb上是不準(zhǔn)確的。
Extra:如果是Only index,這意味著信息只用索引樹中的信息檢索出的,這比掃描整個(gè)表要快。如果是where used,就是使用上了where限制。如果是impossible where 表示用不著where,一般就是沒查出來啥。
如果此信息顯示Using filesort或者Using temporary的話會(huì)很吃力,WHERE和ORDER BY的索引經(jīng)常無法兼顧,如果按照WHERE來確定索引,那么在ORDER BY時(shí),就必然會(huì)引起Using filesort,這就要看是先過濾再排序劃算,還是先排序再過濾劃算。
2.簡單的案例分析
mysql> select * from user where id =1;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 1 | tony | 123456 |
+----+----------+----------+
1 row in set (0.00 sec)
mysql> explain select * from user where id =1;
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
| 1 | SIMPLE | user | const | PRIMARY | PRIMARY | 4 | const | 1 | |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
mysql> select * from `user` where username ="tony";
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 1 | tony | 123456 |
+----+----------+----------+
1 row in set (0.00 sec)
mysql> explain select * from `user` where username ="tony";
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | user | ALL | NULL | NULL | NULL | NULL | 585 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
type=const表示通過索引一次就找到了;
key=primary的話,表示使用了主鍵;
type=all,表示為全表掃描;
key=null表示沒用到索引。type=ref,因?yàn)檫@時(shí)認(rèn)為是多個(gè)匹配行,在聯(lián)合查詢中,一般為REF。