1、开启 show profile
show variables like "profiling";--默认是关闭的 +---------------+-------+ | Variable_name | Value | +---------------+-------+ | profiling | OFF | +---------------+-------+ --开启 set profiling=1;
2、运行指定SQL
我这里运行几条SQL语句,然后运行
show profiles;--会列出所有在这个开启期间执行的SQL,并附上QUERY ID +----------+------------+----------------------------+ | Query_ID | Duration | Query | +----------+------------+----------------------------+ | 1 | 0.00168025 | select * from vhr.employee | | 2 | 0.06573200 | select * from vhr.hr | +----------+------------+----------------------------+ --我们可以看到显示最近操作的两条语句,列表大小由profiling_history_size会话变量控制, 默认值为15.最大值为100
3、诊断具体SQL
show profile cpu,block io for queryid --对应2中的query_id SHOW PROFILE CPU FOR QUERY 1;--查询query_id为1的具体信息 +----------------------+----------+----------+------------+ | Status | Duration | CPU_user | CPU_system | +----------------------+----------+----------+------------+ | starting | 0.000194 | 0.000000 | 0.000000 | | checking permissions | 0.000012 | 0.000000 | 0.000000 | | Opening tables | 0.000030 | 0.000000 | 0.000000 | | init | 0.000053 | 0.000000 | 0.000000 | | System lock | 0.000011 | 0.000000 | 0.000000 | | optimizing | 0.000003 | 0.000000 | 0.000000 | | statistics | 0.000014 | 0.000000 | 0.000000 | | preparing | 0.000010 | 0.000000 | 0.000000 | | executing | 0.000001 | 0.000000 | 0.000000 | | Sending data | 0.001213 | 0.000000 | 0.000000 | | end | 0.000014 | 0.000000 | 0.000000 | | query end | 0.000012 | 0.000000 | 0.000000 | | closing tables | 0.000019 | 0.000000 | 0.000000 | | freeing items | 0.000070 | 0.000000 | 0.000000 | | cleaning up | 0.000025 | 0.000000 | 0.000000 | +----------------------+----------+----------+------------+
日常开发需要注意的结论:
1 converting HEAP to MyISAM : 查询结果太大,内存都不够用了,往磁盘上搬了;
2 creating tmp table : 创建临时表,拷贝数据到临时表,然后再删除;
3 copying to tmp table on disk :把内存中临时表复制到磁盘,危险!!!
4 locked
注:以上四个中若出现一个或多个,表示sql 语句 必须优化。
以上就是实例讲解MySQL 慢查询的详细内容,更多关于MySQL 慢查询的资料请关注其它相关文章!