過年這段時間由於線上資料庫經常壓力過大導致響應非常緩慢甚至死機,咬咬牙下大決心來解決效率不高的問題!
首先是由於公司秉承快速開發原則,頻繁上線,導致每次忽視了效能問題!日積月累,所以導致系統越來越慢,所以如果你的系統查詢語句本來就最佳化的很好了可能參考意義不大!
提取慢查詢記錄檔,應該在你的DataDir目錄下面
通過程式處理慢查詢檔案,將檔案格式的慢查詢匯入到資料庫中:
1 mysql> desc slow_query;
2 +---------------+-------------+------+-----+---------+-------+
3 | Field | Type | Null | Key | Default | Extra |
4 +---------------+-------------+------+-----+---------+-------+
5 | Date | varchar(32) | NO | | | | 查詢發生的時間
6 | user | varchar(64) | NO | | | |
7 | host | varchar(64) | NO | | | |
8 | content | text | NO | | | | 將Statement進行Mask後的語句,
便於Group By
9 | query_time | int(11) | NO | | | | 查詢所用時間,直接效能指標
10 | lock_time | int(11) | YES | | 0 | | 等待鎖定的時間
11 | rows_sent | int(11) | YES | | 0 | | 返回的結果行數
12 | rows_examined | int(11) | YES | | 0 | | 掃描行數
13 | statement | text | YES | | NULL | | 實際查詢語句
14 +---------------+-------------+------+-----+---------+-------+
然後發揮您的想象力在這個表中儘力捕捉你想捕捉的,那類型語句壓力最大、掃描行數最多、等鎖最久……
比如:
最佳化後:
mysql> select sum(query_time)/count(*),count
(*),sum(query_time),min(Date),Max(Date) from slow where Date>'2008-02-20 22:50:52'
and Date<'2008-02-21 17:34:35';
+--------------------------+----------+-----------------+---------------------+---------------------+
| sum(query_time)/count(*) | count(*) | sum(query_time) | min(Date) | Max(Date) |
+--------------------------+----------+-----------------+---------------------+---------------------+
| 5.7233 | 2197 | 12574 | 2008-02-20 22:51:16 | 2008-02-21 17:34:10 |
+--------------------------+----------+-----------------+---------------------+---------------------+
1 row in set (0.09 sec)
最佳化前:
mysql> select sum(query_time)/count(*),count(*),sum(query_time),min(Date),Max(Date) from slow
where Date>'2008-02-17 22:50:52' and Date<'2008-02-18 17:34:35';
+--------------------------+----------+-----------------+---------------------+---------------------+
| sum(query_time)/count(*) | count(*) | sum(query_time) | min(Date) | Max(Date) |
+--------------------------+----------+-----------------+---------------------+---------------------+
| 2.5983 | 16091 | 41810 | 2008-02-17 22:50:58 | 2008-02-18 17:34:34 |
+--------------------------+----------+-----------------+---------------------+---------------------+
1 row in set (0.15 sec)