MySQL

慢查询日志

log_output:日志输出地方,默认FILE(文件),设置TABLE(将日志记录到mysql.slow_log中)
    也可以同时设置,逗号隔开
long_query_time:执行时间超过该配置则记录,单位秒,可适用小数,默认10
log_queries_not_using_indexes:是否将未适用索引的SQL记录到慢查询日志中,默认OFF
log_throttle_queries_not_using_indexes:与log_queries_not_using_indexes配合使用
    限制每分钟写入的SQL数量,默认0
min_examined_row_limit:扫描行数至少达到多少记录才记录到慢查询日志,默认0
log_slow_admin_statements:是否记录管理语句,默认关闭
slow_query_log_file:指定慢查询日志文件路径,默认/var路径
log_slow_slave_statements:从数据库设置,决定是否记录在复制过程中超过long_query_time
    的SQL,如果binlog格式是row,则该参数无效,默认OFF
log_slow_extra:当log_output=FILE时,是否记录额外信息(8.0.14开始提供)
    对TABLE的结果无影响

SQL性能分析

## 查看有无profile
select @@have_profiling;
select @@profiling;
## 启用
set @@profiling = 1;
set profiling_history_size = 100;
## 查看并找到id136
show profiles ;
show profile for query 136;
## 关闭
set @@profiling = 0;
select @@have_profiling;
select @@profiling;
set @@profiling = 1;
set profiling_history_size = 100;
show profiles ;
select state,format(duration,6) as duration 
from information_schema.PROFILING where QUERY_ID = 261 order by SEQ;
## 设置
update performance_schema.setup_instruments
set enabled = 'YES',timed = 'YES'
where name like '%statement/%';

update performance_schema.setup_instruments
set enabled = 'YES',timed = 'YES'
where name like '%stage/%';

update performance_schema.setup_consumers
set enabled = 'YES'
where name like '%events_statements_%';

update performance_schema.setup_consumers
set enabled = 'YES'
where name like '%events_stage%';
## 查询并找到id1164
select event_id,truncate(timer_wait/1000000000000,6) as duration,sql_text
from performance_schema.events_statements_history_long 
where sql_text like '%salaries%';
## 具体信息
select event_name as stage,truncate(timer_wait/1000000000000,6) as duration
from performance_schema.events_stages_history_long 
where nesting_event_id = 1164;
## 开启OPTIMIZER_TRACE功能
set optimizer_trace = 'enabled=on',end_markers_in_json=on;
## 设置要展示的条数
set optimizer_trace_offset = -30,optimizer_trace_limit =30;
## 查询
select * from information_schema.OPTIMIZER_TRACE limit 30;

常用诊断命令

索引

B+Tree特性

创建索引的原则

索引失效

长字段索引优化

单列索引VS组合索引

覆盖索引

重复索引,冗余索引,未使用索引

JOIN优化

分页查询优化

count优化

order by优化(利用索引避免排序)

group by优化

distinct优化

表结构设计

工具

Percona Toolkit

发表评论

发表
Table of Contents