MySQL 是在 5.0.37 版本之后才支持 Show Profile 功能的,如果你不太确定的话,可以通过 select @@have_profiling 查询是否支持该功能。
mysql> select @@have_profiling;
+------------------+
| @@have_profiling |
+------------------+
| YES |
+------------------+
查看是否开启此功能
mysql> select @@profiling;
+-------------+
| @@profiling |
+-------------+
| 0 |
+-------------+
通过set语句在session级别开启此功能
mysql> set session profiling = 1;
Show Profiles 只显示最近发给服务器的 SQL 语句,默认情况下是记录最近已执行的 15 条记录。我们可以重新设置 profiling_history_size 增大该存储记录,最大值为 100。
mysql> show profiles;
+----------+------------+----------------------------------------+
| Query_ID | Duration | Query |
+----------+------------+----------------------------------------+
| 1 | 0.09315150 | show variables like '%profiling%' |
| 2 | 0.00023400 | select @@profiling |
| 3 | 0.00022125 | SELECT DATABASE() |
| 4 | 0.00026300 | select @@profiling |
| 5 | 0.30187700 | show tables |
| 6 | 0.01962900 | select * from farm_record where id |
| 7 | 0.00084600 | select * from farm_record where id > 5 |
+----------+------------+----------------------------------------+
获取到 Query_ID 之后,我们再通过 Show Profile for Query ID 语句,就能够查看到对应 Query_ID 的 SQL 语句在执行过程中线程的每个状态所消耗的时间了。
通过以上分析可知:SELECT COUNT(*) FROM order
; SQL 语句在 Sending data 状态所消耗的时间最长,这是因为在该状态下,MySQL 线程开始读取数据并返回到客户端,此时有大量磁盘 I/O 操作。