MySQL limit的原理

LIMIT M N其原理是

  1. 获取前M+N条数据
  2. offset 抛弃前面 M 条数
  3. 将结果集中的N条数据遍历返回


limit的性能问题

当MySQL limit偏移量较大时,性能就会下降。
其本质是对排好顺序的结果集筛选出其中的区间[M, N]条数据。
所以使用order by 和 group by 再加上limit都会有相同的问题

优化limit性能问题

缩短搜索范围

  1. select * from table_name where (id >= 10000) limit 10

但当有其他过滤条件时不可行

使用索引

利用覆盖索引

Select * From table_name Where id > 
(Select id From table_name where ( user = xxx ))  ORDER BY id LIMIT 100001
limit 10;

使用join替换in

select * from table_name inner join 
( select id from table_name where (user = xxx) 
 limit 10000,10) b using (id)

优化原理

索引文件比数据文件小很多,二三种方法直接取出索引字段定位offset的id