【背景】前端
某業務數據庫load 報警異常,cpu usr 達到30-40 ,居高不下。使用工具查看數據庫正在執行的sql ,排在前面的大部分是:sql
SELECT id, cu_id, name, info, biz_type, gmt_create, gmt_modified,start_time, end_time, market_type, back_leaf_category,item_status,picuture_url FROM relation where biz_type ='0' AND end_time >='2014-05-29' ORDER BY id asc LIMIT 149420 ,20;
表的數據量大體有36w左右,該sql是一個很是典型的排序+分頁查詢:order by col limit N,OFFSET M , MySQL 執行此類sql時須要先掃描到N行,而後再去取 M行。對於此類大數據量的排序操做,取前面少數幾行數據會很快,可是越靠後,sql的性能就會越差,由於N越大,MySQL 須要掃描不須要的數據而後在丟掉,這樣耗費大量的時間。數據庫
【分析】緩存
針對limit 優化有不少種方式,
1 前端加緩存,減小落到庫的查詢操做
2 優化SQL
3 使用書籤方式 ,記錄上次查詢最新/大的id值,向後追溯 M行記錄。
4 使用Sphinx 搜索優化。
對於第二種方式 咱們推薦使用"延遲關聯"的方法來優化排序操做,何謂"延遲關聯" :經過使用覆蓋索引查詢返回須要的主鍵,再根據主鍵關聯原表得到須要的數據。工具
【解決】性能
根據延遲關聯的思路,修改SQL 以下:大數據
優化前優化
root@xxx 12:33:48>explain SELECT id, cu_id, name, info, biz_type, gmt_create, gmt_modified,start_time, end_time, market_type, back_leaf_category,item_status,picuture_url FROM relation where biz_type =\'0\' AND end_time >=\'2014-05-29\' ORDER BY id asc LIMIT 149420 ,20;
+----+-------------+-------------+-------+---------------+-------------+---------+------+--------+-----------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+-------+---------------+-------------+---------+------+--------+-----------------------------+
| 1 | SIMPLE | relation | range | ind_endtime | ind_endtime | 9 | NULL | 349622 | Using where; Using filesort |
+----+-------------+-------------+-------+---------------+-------------+---------+------+--------+-----------------------------+
1 row in set (0.00 sec)
其執行時間:url
優化後:spa
SELECT a.* FROM relation a, (select id from relation where biz_type ='0' AND end_time >='2014-05-29' ORDER BY id asc LIMIT 149420 ,20 ) b where a.id=b.id
root@xxx 12:33:43>explain SELECT a.* FROM relation a, (select id from relation where biz_type ='0' AND end_time >='2014-05-29' ORDER BY id asc LIMIT 149420 ,20 ) b where a.id=b.id;
+----+-------------+-------------+--------+---------------+---------+---------+------+--------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+--------+---------------+---------+---------+------+--------+-------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 20 | |
| 1 | PRIMARY | a | eq_ref | PRIMARY | PRIMARY | 8 | b.id | 1 | |
| 2 | DERIVED | relation | index | ind_endtime | PRIMARY | 8 | NULL | 733552 | |
+----+-------------+-------------+--------+---------------+---------+---------+------+--------+-------+
3 rows in set (0.36 sec)
執行時間:
優化後 執行時間 爲原來的1/3 。