天天看點

【MySQL】 性能優化之 延遲關聯

【背景】

  某業務資料庫load 報警異常,cpu usr 達到30-40 ,居高不下。使用工具檢視資料庫正在執行的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)

其執行時間:

【MySQL】 性能優化之 延遲關聯

優化後:

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)

執行時間:

【MySQL】 性能優化之 延遲關聯

優化後 執行時間 為原來的1/3 。

如果您覺得從這篇文章受益,可以贊助 北在南方 一瓶飲料 ^_^

【MySQL】 性能優化之 延遲關聯