现在的位置: 首页 > 综合 > 正文

MySQL慢查询和慢查询日志分析

2013年05月07日 ⁄ 综合 ⁄ 共 1567字 ⁄ 字号 评论关闭

在实际生产环境中,可能因为开发写了不正确的SQL语句,索引优化的不好,或其他查询操作而导致数据库整体性能下降。

我们只需要分析一下慢查询日志就会知道问题出在哪儿。

登录数据库:

$:mysql -u*** -p****

查看是否启用慢日志记录和状态:

mysql>show variables like "%slow%";

+---------------------+----------------------------+
| Variable_name       | Value                      |
+---------------------+----------------------------+
| log_slow_queries    | ON                         |
| slow_launch_time    | 2                          |
| slow_query_log      | ON                         |
| slow_query_log_file | /data/dbdata/frem-slow.log |
+---------------------+----------------------------+
4 rows in set (0.00 sec)


如上所示,表面数据库已经启用了慢查询记录和日志,slow_query_log_file:/data/dbdata/frem-slow.log这是记录的日志。

/mysql/bin/mysqldumpslow 为慢查询日志分析工具,详细用法:

$:mysql/bin/mysqldumpslow -help

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 #只显示指定的行数,等同于SQL的limit
  -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


按查询行数排序,并取10行排序

mysqldumpslow -s r -t 10 /data/dbdata/frem-slow.log


按查询时间排序,并取20行排序

mysqldumpslow -s t -t 10 /data/dbdata/frem-slow.log


其他的就可以举一反三啦,加上相应参数就可以了。


抱歉!评论已关闭.