先来讲一下Mysql中limit的语法:sql
--语法: SELECT * FROM table LIMIT [offset,] rows | rows OFFSET offset
--举例: select * from table limit 5; --返回前5行 select * from table limit 0,5; --同上,返回前5行 select * from table limit 5,10; --返回6-15行
Mysql中分页主要利用limit可以根据偏移量返回结果的特性:性能
select ... from ... where ... order by ... desc limit pagesize * (page - 1), pagesize; --举例:取t_u_coach表中按coachId降序排列后第5页的教练列表,其中每页10个教练 select * from t_u_coach where id > 10000 order by coachId desc limit 40, 10;
在中小数据量的状况下,惟一须要注意的是coachId和id最好已经创建了聚合索引。优化
可是当数据量很大的时候,limit m,n 的性能随着m的增长而急剧降低。好比:spa
--举例:偏移值过大的时候性能降低 select * from t_u_coach where id > 10000 order by coachId desc limit 40000, 10;
此时,一般有两种方法来进行优化:code
一,使用子查询的方式来进行分页blog
select * from t_u_coach where coachId >= (select coachId from t_u_coach where id > 10000 order by coachId desc limit 40000, 1) limit 10;
二,使用join的方式来进行分页索引
select * from t_u_coach as t1 join (select coachId from t_u_coach where id > 10000 order by coachId desc limit 40000, 1) as t2 where t1.coachId >= t2.coachId order by t1.coachId desc limit 10;
使用子查询来进行分页优化的时候,主要是由于能在子查询中使用索引。
it