order by多個欄位對索引的影響

來源:互聯網
上載者:User

某前台sql語句,簡化後如下
SELECT products_name,products_viewed FROM `products_description`
ORDER BY products_viewed DESC,products_name LIMIT 0,20;

該語句經常大批量出現在慢日誌中!

初步看改語句,非常簡單,根據products_viewed(產品被查看次數)倒序排序,再根據products_name(產品名字)排序!在products_viewed和products_name上分別建立有索引!
但是感覺products_name排序怪怪的!
explain後發現
+----+-------------+----------------------+------+---------------+------+---------+------+-------+----------------+
| id | select_type | table                | type | possible_keys | key  | key_len | ref  | rows  | Extra          |
+----+-------------+----------------------+------+---------------+------+---------+------+-------+----------------+
|  1 | SIMPLE      | products_description | ALL  | NULL          | NULL | NULL    | NULL | 764370 | Using filesort |
+----+-------------+----------------------+------+---------------+------+---------+------+-------+----------------+

改語句做竟然全表掃描!

mysql的order by語句,如果在where條件中沒有合適的索引選擇時,將會選擇order by col中的索引作為條件,但是如果是多個order by組合,將會導致放棄使用索引!
和開發以及需求溝通,發現通過名字排序是可以不需要的!
我們去掉order by後面的 products_name!
再次explain後發現已經能夠使用索引:
explain SELECT products_name,products_viewed FROM `products_description`
 ORDER BY products_viewed LIMIT 0,20;
+----+-------------+----------------------+-------+---------------+-----------------+---------+------+------+-------+
| id | select_type | table                | type  | possible_keys | key            | key_len | ref  | rows | Extra |
+----+-------------+----------------------+-------+---------------+-----------------+---------+------+------+-------+
|  1 | SIMPLE      | products_description | index | NULL          | products_viewed | 5      | NULL |  20 |      |
+----+-------------+----------------------+-------+---------------+-----------------+---------+------+------+-------+

再次對比兩次profiling(過程省略),發現第一次損壞大量io和cpu時間Sorting result上!因為該語句為前台語句,有大量查詢,最佳化後,頁面開啟速度明顯提升!

注意:
1. order by m,n  不要輕易寫這種語句,一般的order by前面的m才是order by的重點,後面的n為配角,如果沒有必要,盡量去掉
2. 參考我的另一篇

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.