MySQL性能优化-分页查询越来越慢


通常我们的分页分页查询时这样的:

select * from table_name limit m,n;

当表的数据很大(几百万或更多)时,分页查询会随m的值变大而时间边长:

select * from bd_user limit 10000, 20;    #耗时0.003秒
select * from bd_user limit 100000, 20;   #耗时0.024秒
select * from bd_user limit 1000000, 20;  #耗时0.25秒
select * from bd_user limit 3000000, 20;  #耗时0.785秒

针对这种问题,我们优化思路如下:

  1. 利用索引列或主键索引做order by 排序
  2. 记住上次查找结果的主键,尽量给出查找范围
  3. 利用覆盖索引和主键索引

所以我们的SQL语句就变成了这样:

select * from bd_user where id>=3000000 order by id limit 0, 20;                                                          #耗时0.001秒
select * from bd_user where id>=(select id from bd_user order by id limit 3000000, 1) order by id limit 0, 20;            #耗时0.413秒
select a.* from bd_user a inner join (select id from bd_user order by id limit 3000000, 20) b on a.id=b.id order by id;   #耗时0.397秒

我们发现,第一条SQL简直要起飞,第二、三条执行效率也提升了一倍。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM