码迷,mamicode.com
首页 > 数据库 > 详细

mysql分页优化

时间:2019-11-23 23:28:51      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:最大值   order   最小   相对   页码   between   主键   查找   最大   

记录当前页最大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;
        

mysql分页优化

标签:最大值   order   最小   相对   页码   between   主键   查找   最大   

原文地址:https://www.cnblogs.com/AbnerLc/p/11920549.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!