SQL执行效率的分析-show profile分析慢查询

olei 698 views 0

show profile

有时候,需要确定SQL慢在哪个环节,此时explain不好确定。在MySQL数据库中,通过profile,能够更清楚了解SQL执行过程中资源使用情况,能让我们知道到底慢在哪个环节

知识拓展:
可以通过设置参数profiling = 1来启用SQL分析。该参数可以在全局和session级别来设置。对于全局级别则作用于整个MySQL实例,而session级别仅影响当前session。该参数开启后,后续执行SQL语句都将记录其资源开销,如IO,上下文切换,CPU,Memory等等。根据这些开销进一步分析当前SQL从而进行优化与调整。

如何使用profile分析慢查询,大致步骤为:确定整个MySQL版本是否支持profile;确定profile是否关闭;开启profile,执行SQL;查看执行完SQLquery id;通过query id查看SQL的每个状态及消耗时间。

  • 确定是否支持profile
mysql> select @@have_profiling;

+------------------+
| @@have_profiling |
+------------------+
| YES              |
+------------------+

1 row in set, 1 warning (0.00 sec)

YES表示支持profile

  • 查看profiling是否关闭
mysql> select @@profiling;

+-------------+
| @@profiling |
+-------------+
|           0 |
+-------------+

1 row in set, 1 warning (0.00 sec)

0表示关闭状态,默认是关闭的

  • 通过set开启profile
mysql> set profiling=1;

Query OK, 0 rows affected, 1 warning (0.00 sec)

Tips:set时没加global,只对当前session有效

  • 执行SQL语句
mysql> select * from t1 where b=1000;
  • 确定SQLquery id

    通过show profile语句确定执行过SQLquery_id

mysql> show profiles;
+----------+------------+-------------------------------+
| Query_ID | Duration   | Query                         |
+----------+------------+-------------------------------+
|        1 | 0.00063825 | select * from t1 where b=1000 |
+----------+------------+-------------------------------+
1 row in set, 1 warning (0.00 sec)
  • 查询SQL执行情况

    通过show profile for query可看到执行过的SQL每个状态和消耗时间

mysql> show profile for query 1;
+----------------------+----------+
| Status               | Duration |
+----------------------+----------+
| starting             | 0.000115 |
| checking permissions | 0.000013 |
| Opening tables       | 0.000027 |
| init                 | 0.000035 |
| System lock          | 0.000017 |
| optimizing           | 0.000016 |
| statistics           | 0.000025 |
| preparing            | 0.000020 |
| executing            | 0.000006 |
| Sending data         | 0.000294 |
| end                  | 0.000009 |
| query end            | 0.000012 |
| closing tables       | 0.000011 |
| freeing items        | 0.000024 |
| cleaning up          | 0.000016 |
+----------------------+----------+
15 rows in set, 1 warning (0.00 sec)

通过上面的结果,可以确定SQL执行过程具体在哪个过程耗时比较久,从而更高的进行SQL优化与调整

发表评论 取消回复
表情 图片 链接 代码

分享