缓存清除
- 命令
reset query cache;
explain命令
- type
system > const > eq_ref > ref > fulltext > ref_or_null > index_merge > unique_subquery > index_subquery > range > index > ALL,一般来说
得保证查询至少达到range级别,最好能达到ref。 - key
若为null,表示没用索引 - rows
只要row足够小,则不会慢
Profiler性能工具
- 开启
show variables like '%profili%';
profiling ON //OFF 表示关闭,NO 表示开启
SET profiling = 1; #开启profiling功能
set session profiling=1;
- 使用
show profiles;#显示记录的profile列表
show profile for query 404#显示指定的profile
运行结果如下
踩坑处理
- 关联字段
表关联时候,相同字段采用同编码、同类型才能使用索引,否则隐式转换,无法使用索引 - 左关联/右关联
能放在on后面的条件,全部放在on,里面,where在on后面执行,放在where会导致运算的数据量大,影响性能 - limit
mysql中limit的基本算法为查到对应的数据后进行分页,如果是limit 10000,10;则会查询10000条数据,适合采用延迟关联的写法,例子如下
SELECT * FROM cms_discovery_nicegoods_single_recommend a JOIN (select id from cms_discovery_nicegoods_single_recommend limit 500000, 20) b ON a.ID = b.id
select * from cms_discovery_nicegoods_single_recommend a , (select id from cms_discovery_nicegoods_single_recommend limit 500000,20) as b where a.id = b.id
- %模糊查询
代码中禁止左边出现%,因为会出现全表扫描。 - %避免负向查询
负向查询条件:NOT、!=、<>、!<、!>、NOT IN、NOT LIKE等,会导致全表扫描
show global status(命令解析)
show global status like 'table_locks%'; 锁表情况
show global status like 'handler_read%'; 表扫描情况
show global status like 'created_tmp%'; 临时表
show variables like ‘key_buffer_size’; key_buffer_size是对MyISAM表性能影响最大的一个参数
show variables like '%slow%'; 慢查询