MYSQL入门到精通【8】:mysql语句之慢查询优化

MYSQL入门到精通【8】:mysql语句之慢查询优化

1. 慢查询

(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=361680show 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;

在这里插入图片描述
在这里插入图片描述

2. 数据库缓存

(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;
# 第二次查询变快了,因为第一次数据缓存了

在这里插入图片描述
(2) 关闭缓存状态

set global query_cache_size=0;  
show variables like '%cache%'; # 缓存关闭,默认状态

3. 其他优化

(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

在这里插入图片描述
(2) 针对性查询

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' ; 
# 说明 不要在字段上加运算

在这里插入图片描述
(5) 注意事项
左模糊全模糊不会用索引查询,而右查询可以

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值