简述
MySQL慢查询,又叫慢查询日志,是MySQL提供的一种日志记录,用来记录在MySQL中响应时间超过阀值的语句。可以设置long_query_time的值,运行时间超过long_query_time值的SQL语句,就会被记录到慢查询日志中,默认为10秒。
注意
Mysql默认不开启慢查询日志,需要手动来设置开启,不过如果没有数据库调优的需要,一般是不开启的,因为慢查询日志会带来一定的性能影响。
参数
slow_query_log
是否开启慢查询日志,1表示开启,0表示关闭。
show variables like '%slow_query_log%';
使用set global slow_query_log=1开启了慢查询日志只对当前数据库生效,MySQL重启后则会失效。如果要永久生效,就必须修改配置文件my.cnf。
slow_query_log_file
这个参数用于指定慢查询日志的存放路径,缺省为host_name-slow.log文件。
show variables like 'slow_query_log_file';
long_query_time
开启了慢查询日志后,默认情况下long_query_time的值为10秒,可以使用命令修改,也可以在my.cnf参数里面修改。运行时间正好等于long_query_time的情况,并不会被记录下来。
show variables like 'long_query_time%';
//设置
set global long_query_time=4;
注:使用命令 set global long_query_time=4修改后,需要重新连接或新开一个会话才能看到修改值。
log_output
log_output参数指定日志的存储方式。log_output=‘FILE’表示将日志存入文件,默认值也是’FILE’。日志记录到系统的专用日志表中,要比记录到文件耗费更多的系统资源。
show variables like '%log_output%';
//设置
set global log_output='TABLE';
log-queries-not-using-indexes
该系统变量指定未使用索引的查询也被记录到慢查询日志中。
show variables like 'log_queries_not_using_indexes';
//设置
set global log_queries_not_using_indexes=1;
log_slow_admin_statements
这个系统变量表示,是否将慢管理语句例如ANALYZE TABLE和ALTER TABLE等记入慢查询日志。
show variables like 'log_slow_admin_statements';
Slow_queries
查询有多少条慢查询记录。
show global status like '%Slow_queries%';
mysqldumpslow工具
MySQL提供了日志分析工具mysqldumpslow,用来帮助分析慢查询日志。
Usage: mysqldumpslow [ OPTS... ] [ LOGS... ]
Parse and summarize the MySQL slow query log. Options are
--verbose verbose
--debug debug
--help write this text to standard output
-v verbose
-d debug
-s ORDER what to sort by (al, at, ar, c, l, r, t), 'at' is default(排序方式)
al: average lock time(平均锁定时间)
ar: average rows sent(平均返回记录数)
at: average query time(平均查询时间)
c: count(访问计数)
l: lock time(锁定时间)
r: rows sent(返回记录)
t: query time(查询时间)
-r reverse the sort order (largest last instead of first)
-t NUM just show the top n queries(返回前面n条数据)
-a don't abstract all numbers to N and strings to 'S'
-n NUM abstract numbers with at least n digits within names
-g PATTERN grep: only consider stmts that include this string(正则匹配模式,大小写不敏感)
-h HOSTNAME hostname of db server for *-slow.log filename (can be wildcard),
default is '*', i.e. match all
-i NAME name of server instance (if using mysql.server startup script)
-l don't subtract lock time from total time