某前台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为配角,如果没有必要,尽量去掉