记录当前页最大id和最小id进行优化
原理是,记录住当前页id的最大值和最小值,计算跳转页面和当前页相对偏移,由于页面相近,这个偏移量不会很大,这样的话m值相对较小,大大 减少扫描的行数。
假设每一页只有10条数据,当前页码数是5,那么最大id是50,最小id是40,只要上一页和下一页
查找下一页 select * from score where sid > 50 LIMIT 10; 查找上一页 select * from score where sid > 50 LIMIT 10; 使用 between and 查找数量不一定够10条,因为id不连续
假设每一页只有10条数据,当前页码数是5,那么最大id是50,最小id是40,然后跳到第8页或者第2页
跳到第8页 以最大值为基准 select * from tb1 where nid < ( select nid from (select nid from tb1 where nid > 50 limit 30) A order by A.nid desc limit 1 ) # 通过当前页取第8页最大id order by tb1.nid desc limit 10; 以最小值为基准 select * from tb1 where nid > ( select nid from (select nid from tb1 where nid > 40 limit 30) A order by A.nid desc limit 1 ) # 通过当前页取第8页最小id order by tb1.nid asc limit 10; 代码分解: select nid from tb1 where nid > 50 limit 30 # 通过主键id获取当前页到跳转页最大值id的行数t1, select nid from t1 order by A.nid desc limit 1 # 然后倒序取t1中的最大值,max_id or min_id select * from tb1 where nid < max_id order by tb1.nid desc limit 10; 或者 select * from tb1 where nid > min_id order by tb1.nid asc limit 10; 跳到第2页 以最大页为基准 select * from tb1 as t where nid < (select nid from (select nid from tb1 as t1 where t.nid < 50 limit 30 order by t1.nid desc) A order by A.nid asc limit 1) # 通过当前页取第2页最大id order by nid desc limit 10; 以最小页为基准 select * from tb1 as t where nid > ( select nid from (select nid from tb1 as t1 where nid < 40 limit 30 order by t1.nid desc) A order by A.nid asc limit 1) # 通过当前页取第2页最小id limit 10; 代码分解 select nid from tb1 as t1 where nid < 40 limit 30 order by t1.nid desc # 结果为t1,因为倒序,结果是从大到小, select nid from t1 A order by A.nid asc limit 1 # 因为是倒序,想取最小值,还得再排序,然后取t1中的max_id or min_id select * from tb1 where nid < max_id order by tb1.nid desc limit 10; 或者 select * from tb1 where nid > min_id order by tb1.nid asc limit 10;