以前一直以為在order by的字段上加上索引就行了,網上搜也是,實際上使用的時候在查詢中如果使用了ORDER BY 語句,如果在select中有未加入索引的字段,使用order by以後就不會走索引,而會進行全表掃描。
單表的話可以在from字段後加入FORCE INDEX(key)字段,就能強制使用索引。
使用前
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+
| 1 | SIMPLE | t_sms | ALL | NULL | NULL | NULL | NULL | 107 | Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+
type時all,代表全表掃描
extra使用的是Using filesort。檔案排序。這項效率非常低
使用後
+----+-------------+-------+-------+---------------+-----------------+---------+------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+-----------------+---------+------+------+-------+
| 1 | SIMPLE | t_sms | index | NULL | sms_create_time | 9 | NULL | 10 | |
+----+-------------+-------+-------+---------------+-----------------+---------+------+------+-------+
使用後type就是index了,說明走了索引,并且extra沒有值,說明檔案順序和order by字段順序一直,不需要額外的操作