MySQL慢查詢日誌的方法

來源:互聯網
上載者:User

MySQL慢查詢日誌的方法

前言:以前介紹了通過工具mysqldumpslow分析慢查詢日誌的方法,隨著工作的進展又發現了另外一個更加好用的方法:把慢日誌記錄到mysql資料庫中。

MySQL 慢日誌查詢工具之mysqldumpslow 

方法介紹:通過設定參數log_output可以定義mysql的慢查詢日誌是存放在檔案還是資料表中;

mysql> show variables like 'log_output';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_output    | FILE  |
+---------------+-------+
1 row in set (0.00 sec)

註:Value值是輸出的格式,當前的Value值為FILE說明把慢查詢日誌存放在OS的檔案中;

mysql> set global log_output='TABLE';
Query OK, 0 rows affected (0.00 sec)

註:設定當前的輸出為mysql中的表;

mysql> show variables like 'log_output';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_output    | TABLE |
+---------------+-------+
1 row in set (0.00 sec)

註:現在輸出為mysql中的表了;

測試:

建議:slow_log建立時候預設的資料庫引擎是CSV,該引擎的查詢效率比較低,可以修改成MyISAM;

mysql> select * from mysql.slow_log;


CREATE TABLE `slow_log` (
  `start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `user_host` mediumtext NOT NULL,
  `query_time` time NOT NULL,
  `lock_time` time NOT NULL,
  `rows_sent` int(11) NOT NULL,
  `rows_examined` int(11) NOT NULL,
  `db` varchar(512) NOT NULL,
  `last_insert_id` int(11) NOT NULL,
  `insert_id` int(11) NOT NULL,
  `server_id` int(10) unsigned NOT NULL,
  `sql_text` mediumtext NOT NULL
) ENGINE=CSV DEFAULT CHARSET=utf8 COMMENT='Slow log';
 

整理了一個常用的語句:使用次數進行排序慢查詢的sql語句

mysql> select sql_text, count(1),avg(query_time),avg(rows_sent),avg(rows_examined)
from slow_log
group by (sql_text)
order by avg(query_time) desc

本文永久更新連結地址:

相關文章

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.