版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yaonga/article/details/83819345
在设计数据库和表的过程中,表结构难免会存在考虑不全等,再者可能我们的SQL语句存在慢查询,这个时候就需要对我们执行的SQL语句进行具体分析,而分析问题的关键的前提是先找出该慢查询SQL语句,才能对症下药。
MySQL优化流程
1.通过MySQL慢查询日志,找到慢查询的SQL语句
- 编辑MySQL(5.6)vim /etc/my.cnf添加配置开启慢查询日志:
slow_query_log=ON
slow_query_log_file=/var/log/mysql/slow.log
long_query_time=1
slow_query_log:开启日志功能
slow_query_log_file:记录日志的文件
long_query_time:设定慢查询的时间(单位:秒)
然后,重启MySQL
- 开启监测日志命令
tail -100f slow.log
- 登陆MySQL,模拟慢查询sql
mysql> select sleep(5);
+----------+
| sleep(5) |
+----------+
| 0 |
+----------+
1 row in set (5.00 sec)
- 查看日志控制台输出:
# Time: 181106 18:10:03
# User@Host: root[root] @ localhost [] Id: 2
# Query_time: 5.001387 Lock_time: 0.000000 Rows_sent: 1 Rows_examined: 0
SET timestamp=1541556603;
select sleep(5);
这里面记录慢查询执行时间,慢查询语句等信息,对应地就能找到和分析慢查询SQL语句。
2.使用explain 命令去查看慢查询SQL语句的执行计划
- 通过explain查看执行计划的信息,是否用到索引,已经索引用到的级别程度
EXPLAIN SELECT * FROM student where name like "yalong"
结果集:
3.使用 show profile[s] 查看慢查询SQL 的性能使用情况
- 开启 profile 功能
set profiling=1; --1 是开启、0 是关闭
- 执行 show profiles
mysql> show profiles;
+----------+------------+-----------------------+
| Query_ID | Duration | Query |
+----------+------------+-----------------------+
| 1 | 0.00013625 | select * from student |
| 2 | 0.00025450 | select * from student |
+----------+------------+-----------------------+
指定分析哪个命令:show profile for query 2
4.根据前三部,优化指定的SQL;