MySQL数据库优化
1、优化步骤
- 慢查询的开启并捕获;
- explain+慢SQL分析;
- show profile查询SQL在Mysql服务器里面的执行细节和生命周期情况;
- SQL数据库服务器的参数调优。
2、索引优化口诀
- 全值匹配我最爱;
- 左前缀法则:带头大哥不能死,中间兄弟不能断;
- 索引列上不计算(计算、函数、自动或手动类型转换);
- 范围之后全失效;
- 尽量使用覆盖索引(减少select *);
- mysql 不等于(!= 或 <>)会全表扫描;
- is null,is not null 索引会失效;
- like % 加右边;
- 字符串里有引号;
- 少用or,用它索引会失效;
【优化总结口诀】
全值匹配我最爱,最左前缀要遵守;
带头大哥不能死,中间兄弟不能断;
索引列上少计算,范围之后全失效;
Like百分写最右,覆盖索引不写星;
不等空值还有or,索引失效要少用。
3、Explain 执行计划
3.1、Extra
- Using filesort; [性能差] 文件排序(需要尽快优化)
- Using temporary; [性能差] 使用了临时表保存中间结果 。常见于排序和分组中。(如果可以的话,必须优化)
- Using index;[性能好]
- Using where;
- Using join buffer; 使用了连接缓存(可考虑调整Buffer大小);
- impossible where;(比如:select * from a where name=‘123’ and name=‘456’)
- select tables optimized away;
- distinct;
4、技巧
4.1、永远小表驱动大表
# B是小表
select * from A where id in (select id from B)# A是小表
select * from A where exists(select 1 from B where B.id=A.id)