所谓慢查询即一条sql语句的查询时间超过了预定义好的规定查询时间,这些语句是要记录下来做语句优化使用的,下面是如何记录慢查询语句的方法:
1、先查看是否开启慢查询日志功能:
mysql> show global variables like ‘slow_query_log‘;
+----------------+-------+
| Variable_name | Value |
+----------------+-------+
| slow_query_log | OFF |
+----------------+-------+
1 row in set (0.00 sec)
如果没有开启可以在sql命令界面直接打开:
mysql> set global slow_query_log=1;
Query OK, 0 rows affected (0.00 sec)
mysql> show global variables like ‘slow_query_log‘; #开启慢查询日志记录的命令
+----------------+-------+
| Variable_name | Value |
+----------------+-------+
| slow_query_log | ON | # slow_query_log的值为on表示已经开启
+----------------+-------+
1 row in set (0.00 sec)
2、定义时间SQL查询的超时时间:
查看默认为多少秒:
mysql> show global variables like ‘long_query_time‘;
+-----------------+-----------+
| Variable_name | Value |
+-----------------+-----------+
| long_query_time | 10.000000 | #默认为10秒,时间太长,我设置为2秒
+-----------------+-----------+
1 row in set (0.00 sec)
mysql> set global long_query_time = 2;
Query OK, 0 rows affected (0.00 sec)
mysql> show global variables like ‘long_query_time‘;
+-----------------+----------+
| Variable_name | Value |
+-----------------+----------+
| long_query_time | 2.000000 | #将超时时间设置为2秒
+-----------------+----------+
1 row in set (0.00 sec)
3、查看慢查询日志的保存路径:
mysql> show global variables like ‘slow_query_log_file‘;
+---------------------+-----------------------------+
| Variable_name | Value |
+---------------------+-----------------------------+
| slow_query_log_file | /mydata/data/node9-slow.log |
+---------------------+-----------------------------+
1 row in set (0.01 sec)
4、测试效果:
先模拟执行一条命令睡眠4秒钟:
mysql> select sleep(4);
+----------+
| sleep(4) |
+----------+
| 0 |
+----------+
1 row in set (4.00 sec)
然后查看这条慢查询日志是否会被记录在慢查询日志当中:
[[email protected] ~]# cat /mydata/data/node9-slow.log
# Time: 150408 9:22:41
# [email protected]: root[root] @ localhost [] Id: 1
# Query_time: 4.001110 Lock_time: 0.000000 Rows_sent: 1 Rows_examined: 0
SET timestamp=1428456161;
select sleep(4); #已经被记录到日志当中,生成环境可以记录慢查询语句,适当做SQL查询语句优化,如使用where语句或like语句做精确查询。