(1) 基本介绍
查询日志太慢,就开启慢查询来记录
show databases;
use test;
show tables;
use account;
show variables like '%slow%'; # 慢查询,见图①
set global log_slow_queries=on; # 打开慢查询,见图②
show variables like '%slow%';
show variables like '%long%'; # 查看查询时间
set long_query_time=0.5; # 设置查询时间阈值
show variables like '%long%';
(2) 分析查询慢的方法:profiling
#
desc account;
explain select * from account where pid=361680\G
# 查询慢
explain select * from account where pid=361680\G
#查询快
explain select * from account where account_id=361680\G
# 查询快慢的区别:在 type 和 rows 方面差别较大
show variables like '%profiling%';
set profiling=ON; # 打开
show variables like '%profiling%';
#查询慢
explain select * from account where pid=361680;
show profiles;
show profile for query 2; # 执行操作所有时间
(3) 慢查询优化
关键:where后面的字段加索引
alter table account add index(pid);
explain select * from account where account_id='361680'\G # pid 是 varchar 型
show profiles;
show profiles for query 17;
(1) 缓存开启状态
show variables like '%cache%'; # 查看缓存,关闭状态
show status like '%qcache%'; # 查看命中率
set global query_cache_size=10240000; # 打开缓存
show variables like '%cache%';
show status like '%qcache%'; # 查看命中率
select count(*) from account;
select count(*) from account;
# 第二次查询变快了,因为第一次数据缓存了
set global query_cache_size=0;
show variables like '%cache%'; # 缓存关闭,默认状态
(1) 添加索引
explain select * from account where pid='240691' or passpord='limeiling123'\G
# 添加索引
alter table account add index(passport);
explain select * from account where pid='240691' or passpord='limeiling123'\G
select * from account where pid='240691' ; # 查询慢
select pid from account where pid='240691' ; # 针对性查询,推荐
show profiles;
# 总结: 需要什么字段 就查什么字段
(3) limit
select pid,passport from account where pid='240691' limit 1 ;
(4) 字段中不要添加运算
select pid,passport from account where pid+1='240691' ;
# 说明 不要在字段上加运算