一、慢查询:
1.紧急且重要:show full processlist 在数据库出现问题时现场抓取数据库 隔2s执行一次
2.重要不紧急:分析慢查询日志
配置参数记录:
long_query_time:2 #执行超过2s的记录到log里
long_queries_not_using_indexes #没有走索引的记录到log里
log-show-queries = /data/slow.log #log文件
二、explain语句检查索引执行情况:
explain select * from table where name='jack';
explain select SQL_NO_CACHE * from test where name='jack';
三、对需要创建索引的列创建索引
生产场景,超过百万的表不能在高峰期创建索引
四、分析慢查询的工具mysqlsla
切割慢查询日志:
mv /data/slow.log /opt/($date+%F)_slow.log
mysqladmin -uroot -proot -S /data/mysql.sock flush-logs
遇到生产环境比如网站卡死的情况,查看服务器负载、I/O以及数据库。如果定位到出现问题的是数据库方面,那么使用show full processlist 查出出问题的sql,根据具体情况进行优化。
例如出现问题的sql是select * from table where a='xxx' and b='yyy' and c='2020-06-20';考虑创建联合索引
select count(distinct a) from table
select count(distinct b) from table
select count(distinct c) from table
看下各列所占的不重复数字,决定于索引的顺序(或是是否适合作为索引列)