MySQL在5.0之后有个分析查询语句非常重要的利器,就是profiling。
要是用profiling,我们首先要打开profiling。
set profiling=on;
设置了profiling之后,你的每一个sql语句都会被记录分析。使用show profiles;
可以查看在打开profiling之后所有被记录的操作。(这里只是为了举例,使用了非常简单的查询)
+----------+------------+--------------------+
| Query_ID | Duration | Query |
+----------+------------+--------------------+
| 1 | 0.00007075 | select * from test |
| 2 | 0.00005275 | show tables |
| 3 | 0.00025975 | show databases |
| 4 | 0.00011925 | SELECT DATABASE() |
| 5 | 0.00018650 | show databases |
| 6 | 0.00009825 | show tables |
| 7 | 0.00020875 | select * from test |
| 8 | 0.00005250 | show profilings |
| 9 | 0.00005025 | show profilies |
+----------+------------+--------------------+
可以看到MySQL为每一个操作生成了一个Query_ID,我们可以使用show profile for query 7
这样的形式来查看第七条语句具体的执行过程分析。
+----------------------+----------+
| Status | Duration |
+----------------------+----------+
| starting | 0.000051 |
| checking permissions | 0.000006 |
| Opening tables | 0.000019 |
| init | 0.000017 |
| System lock | 0.000008 |
| optimizing | 0.000005 |
| statistics | 0.000011 |
| preparing | 0.000009 |
| executing | 0.000002 |
| Sending data | 0.000051 |
| end | 0.000003 |
| query end | 0.000005 |
| closing tables | 0.000006 |
| freeing items | 0.000008 |
| cleaning up | 0.000008 |
+----------------------+----------+
可以看到MySQL为我们生成了操作在执行过程中每一个步骤所耗费的时间,通过profiling我们就可以查找出sql语句中耗时的地方,并加以优化。
以下状态解释来自网络博客:
状态 | 描述 |
---|---|
System lock | 确认是由于哪个锁引起的,通常是因为MySQL或InnoDB内核级的锁引起的建议:如果耗时较大再关注即可,一般情况下都还好 |
Sending data | 从server端发送数据到客户端,也有可能是接收存储引擎层返回的数据,再发送给客户端,数据量很大时尤其经常能看见,备注:Sending Data不是网络发送,是从硬盘读取,发送到网络是Writing to net。建议:通过索引或加上LIMIT,减少需要扫描并且发送给客户端的数据量 |
Sorting result | 正在对结果进行排序,类似Creating sort index,不过是正常表,而不是在内存表中进行排序建议:创建适当的索引 |
Table lock | 表级锁,没什么好说的,要么是因为MyISAM引擎表级锁,要么是其他情况显式锁表 |
create sort index | 当前的SELECT中需要用到临时表在进行ORDER BY排序。建议:创建适当的索引 |
checking query cache for querychecking privileges on cachedsending cached result to clienstoring result in query cache | 和query cache相关的状态,已经多次强烈建议关闭 |