五、SQL 执行分析
5.1、SQL 执行时间分析
通过找到执行时间长的 SQL 语句,可以直观的发现数据层的效率问题。
①、通过 show processlist 来查看系统的执行情况
②、通过 profiling 来进行查看
这个命令是查看 SQL 的执行时间,能很直观的看出快慢。
A 查看 profiling 是否开启
0 代表还是关闭着分析功能mysql> select @@profiling;
+-------------+
| @@profiling |
+-------------+
| 0 |
+-------------+
B 打开工具mysql> set profiling=1;
Query OK, 0 rows affected (0.00 sec)
mysql> select @@profiling;
+-------------+
| @@profiling |
+-------------+
| 1 |
+-------------+
1 row in set (0.00 sec)
C 查看 SQL 的执行时间mysql> show profiles;
+----------+------------+--------------------+
| Query_ID | Duration | Query |
+----------+------------+--------------------+
| 1 | 0.00032000 | select @@profiling |
+----------+------------+--------------------+
D 查看 SQL 执行耗时详细信息show profile for query Query_IDmysql> show profile for query 1;
+----------------------+----------+
| Status | Duration |
+----------------------+----------+
| starting | 0.000073 |
| checking permissions | 0.000031 | ---检查是否在缓存中
| Opening tables | 0.000207 | ---打开表
| init | 0.000067 | ---初始化
| System lock | 0.000040 | ---锁系统
| optimizing | 0.000005 | ---优化查询
| statistics | 0.000021 |
| preparing | 0.000015 | ---准备
| executing | 0.000003 | ---执行
| Sending data | 0.000993 |
| end | 0.000006 |
| query end | 0.000007 |
| closing tables | 0.000011 |
| freeing items | 0.000169 |
| cleaning up | 0.000089 |
+----------------------+----------+
以上具体的信息都是从 INFORMATION_SCHEMA.PROFILING 这张表中取得的。这张表记录了所有的各个步骤的执行时间及相关信息。语法:select * from INFORMATION_SCHEMA.PROFILING where query_id = Query_ID;
③、慢查询日志
MySQL 的慢查询日志,顾名思义就是把执行时间超过设定值(默认为10s)的 SQL 记录到日志中。这项功能需要手动开启,但是开启后会造成一定的性能损耗。
A 查看慢日志是否开启
默认情况下slow_query_log的值为OFF,表示慢查询日志是禁用的,可以通过设置slow_query_log的值来开启。mysql> show variables like "%slow_query_log%"