guopengfa
发布于 2021-05-25 / 506 阅读 / 0 评论 / 0 点赞

MySql查询优化浅入

有表table,有自增id,测试不同起点查询固定条数速度:

select * from news table by id desc limit 0,10
耗时0.003秒
select * from news table by id desc limit 10000,10
耗时0.058秒
select * from news table by id desc limit 100000,10 
耗时0.575秒
select * from news table by id desc limit 1000000,10
耗时7.28秒
  • 可以看出当我们起点从一百万开始时间就需要7秒钟,非常的慢了
  • 我们现在进行查询优化

优化一

select * from news 
where id >  (select id from news order by id desc  limit 1000000, 1)
order by id desc 
limit 0,10
  • 查询时间 0.365秒,提升效率是非常明显的!!原理是什么呢???

  • 我们使用条件对id进行了筛选,在子查询 (select id from news order by id desc limit 1000000, 1) 中我们只查询了id这一个字段比起select * 或 select 多个字段 节省了大量的查询开销!

优化二

select * from news 
where id  between 1000000 and 1000010 
order by id desc
  • 速度0.2s,但是不适用于id不连续的表

————————————————
参考链接:https://blog.csdn.net/qq_35472110/article/details/80832304


评论