MySQL高性能的索引策略(四)mysql
使用索引掃描來作排序sql
mysql有兩種方式能夠生成有序的結果:經過排序操做;或者經過索引順序掃描;若是explain出來的type列的值爲index,則說明mysql使用了索引掃描來作排序(不要和Extra 列的「using index」搞混淆了)。性能
掃描索引自己是很快的,由於只需從一條記錄移動到緊接着的下一條記錄。但若是索引不能覆蓋查詢所需的所有列,那就不得不每掃描一條索引記錄就得回表查詢一次對應的行。這基本上都是隨機IO,所以按索引順序讀取數據的速度一般比順序的全表掃描慢,尤爲是在IO密集型的工做負載時。spa
mysql可使用同一個索引既知足排序,又用於查找行。所以若是可能,設計索引時應該儘量的知足這兩種任務。設計
只有當索引的列的順序和order by子句的順序徹底一致,而且全部列的排序方向(倒序和正序)都同樣時,mysql才能使用索引來對結果作排序。code
若是查詢須要關聯多張表,則只有order by子句引用的字段所有爲第一個表時,才能使用索引來作排序。排序
order by子句和查找型查詢的限制時同樣的:須要知足索引的最左前綴的要求;不然,mysql都須要執行排序操做,而沒法利用索引排序。索引
有一種狀況下order by子句能夠不知足索引的最左前綴要求,就是前導列爲常量的時候。it
若是where子句或者join子句中對這些列指定了常量,就能夠彌補索引的不足。table
> explain select id from article where title = 'hello world' order by shortName asc ******************** 1. row ********************* id: 1 select_type: SIMPLE table: article type: ref possible_keys: idx_short_name_title key: idx_short_name_title key_len: 257 ref: const rows: 5 Extra: Using where; Using index 1 rows in set
就如上面這個sql語句同樣,雖然order by子句不能知足索引的最左前綴的要求,也能夠用於查詢排序,這是由於索引的第一列被指定爲一個常數。就是 title = 'hello world';
就如上面的結果顯示的那樣,在explain的結果中,沒有出現using filesort。
咱們來對照一下區別,
> explain select id from article order by title asc ******************** 1. row ********************* id: 1 select_type: SIMPLE table: article type: index possible_keys: key: idx_short_name_title key_len: 514 ref: rows: 5 Extra: Using index 1 rows in set
order by的列和索引的列的順序一致。沒有出現using filesort。
> explain select id from article order by shortName asc ******************** 1. row ********************* id: 1 select_type: SIMPLE table: article type: index possible_keys: key: idx_short_name_title key_len: 514 ref: rows: 5 Extra: Using index; Using filesort 1 rows in set
order by的列的順序和索引列的順序不一致,因此出現using filesort。
可是當查詢的列不能所有被索引覆蓋時,雖然指定索引列的前導列爲常量,order by列的順序和索引列其他的一致,但也是會出現using filesort。
> explain select id,totalView from article where title = 'hello world' order by shortName asc ******************** 1. row ********************* id: 1 select_type: SIMPLE table: article type: ALL possible_keys: idx_short_name_title key: key_len: ref: rows: 5 Extra: Using where; Using filesort 1 rows in set
==========END==========