MySQL深分页问题解决的实战记录

目录
    • 回顾b+ 树结构
  • inner join 延迟关联

          前言

          我们日常做分页需求时,一般会用limit实现,但是当偏移量特别大的时候,查询效率就变得低下。本文将分4个方案,讨论如何优化mysql百万数据的深分页问题,并附上最近优化生产慢sql的实战案例。

          limit深分页为什么会变慢?

          先看下表结构哈:

          create table account (
            id int(11) not null auto_increment comment '主键id',
            name varchar(255) default null comment '账户名',
            balance int(11) default null comment '余额',
            create_time datetime not null comment '创建时间',
            update_time datetime not null on update current_timestamp comment '更新时间',
            primary key (id),
            key idx_name (name),
            key idx_update_time (update_time) //索引
          ) engine=innodb auto_increment=1570068 default charset=utf8 row_format=redundant comment='账户表';
          

          假设深分页的执行sql如下:

          select id,name,balance from account where update_time> '2020-09-19' limit 100000,10;
          

          这个sql的执行时间如下:

          执行完需要0.742秒,深分页为什么会变慢呢?如果换成 limit 0,10,只需要0.006秒哦

          我们先来看下这个sql的执行流程:

          1. 通过普通二级索引树idx_update_time,过滤update_time条件,找到满足条件的记录id。
          2. 通过id,回到主键索引树,找到满足记录的行,然后取出展示的列(回表)
          3. 扫描满足条件的100010行,然后扔掉前100000行,返回。

          sql的执行流程

          执行计划如下:

          sql变慢原因有两个:

          1. limit语句会先扫描offset+n行,然后再丢弃掉前offset行,返回后n行数据。也就是说limit 100000,10,就会扫描100010行,而limit 0,10,只扫描10行。
          2. limit 100000,10 扫描更多的行数,也意味着回表更多的次数。

          通过子查询优化

          因为以上的sql,回表了100010次,实际上,我们只需要10条数据,也就是我们只需要10次回表其实就够了。因此,我们可以通过减少回表次数来优化。

          回顾b+ 树结构

          那么,如何减少回表次数呢?我们先来复习下b+树索引结构哈~

          innodb中,索引分主键索引(聚簇索引)和二级索引

          • 主键索引,叶子节点存放的是整行数据
          • 二级索引,叶子节点存放的是主键的值。

          把条件转移到主键索引树

          如果我们把查询条件,转移回到主键索引树,那就不就可以减少回表次数啦。转移到主键索引树查询的话,查询条件得改为主键id了,之前sql的update_time这些条件咋办呢?抽到子查询那里嘛~

          子查询那里怎么抽的呢?因为二级索引叶子节点是有主键id的,所以我们直接根据update_time来查主键id即可,同时我们把 limit 100000的条件,也转移到子查询,完整sql如下:

          select id,name,balance from account where id >= (select a.id from account a where a.update_time >= '2020-09-19' limit 100000, 1) limit 10;
          

          查询效果一样的,执行时间只需要0.038秒!

          我们来看下执行计划

          由执行计划得知,子查询 table a查询是用到了idx_update_time索引。首先在索引上拿到了聚集索引的主键id,省去了回表操作,然后第二查询直接根据第一个查询的 id往后再去查10个就可以了!

          因此,这个方案是可以的~

          inner join 延迟关联

          延迟关联的优化思路,跟子查询的优化思路其实是一样的:都是把条件转移到主键索引树,然后减少回表。不同点是,延迟关联使用了inner join代替子查询。

          优化后的sql如下:

          select  acct1.id,acct1.name,acct1.balance from account acct1 inner join (select a.id from account a where a.update_time >= '2020-09-19' order by a.update_time limit 100000, 10) as  acct2 on acct1.id= acct2.id;
          

          查询效果也是杠杆的,只需要0.034秒

          执行计划如下:

          查询思路就是,先通过idx_update_time二级索引树查询到满足条件的主键id,再与原表通过主键id内连接,这样后面直接走了主键索引了,同时也减少了回表。

          标签记录法

          limit 深分页问题的本质原因就是:偏移量(offset)越大,mysql就会扫描越多的行,然后再抛弃掉。这样就导致查询性能的下降。

          其实我们可以采用标签记录法,就是标记一下上次查询到哪一条了,下次再来查的时候,从该条开始往下扫描。就好像看书一样,上次看到哪里了,你就折叠一下或者夹个书签,下次来看的时候,直接就翻到啦。

          假设上一次记录到100000,则sql可以修改为:

          select  id,name,balance from account where id > 100000 order by id limit 10;
          

          这样的话,后面无论翻多少页,性能都会不错的,因为命中了id索引。但是你,这种方式有局限性:需要一种类似连续自增的字段。

          使用between…and…

          很多时候,可以将limit查询转换为已知位置的查询,这样mysql通过范围扫描between…and,就能获得到对应的结果。

          如果知道边界值为100000,100010后,就可以这样优化:

          select  id,name,balance from account where id between 100000 and 100010 order by id desc;
          

          手把手实战案例

          我们一起来看一个实战案例哈。假设现在有表结构如下,并且有200万数据.

          create table account (
           id varchar(32) collate utf8_bin not null comment '主键',
           account_no varchar(64) collate utf8_bin not null default '' comment '账号'
           amount decimal(20,2) default null comment '金额'
           type varchar(10) collate utf8_bin default null comment '类型a,b'
           create_time datetime default null comment '创建时间',
           update_time datetime default null comment '更新时间',
           primary key (id),
           key `idx_account_no` (account_no),
           key `idx_create_time` (create_time)
           ) engine=innodb default charset=utf8 collate=utf8_bin comment='账户表' 
          

          业务需求是这样:获取最2021年的a类型账户数据,上报到大数据平台。

          一般思路的实现方式

          很多伙伴接到这么一个需求,会直接这么实现了:

          //查询上报总数量
          integer total = accountdao.countaccount();
          
          //查询上报总数量对应的sql
          <select id ='countaccount' resulttype="java.lang.integer">
            seelct count(1) 
            from account
            where create_time >='2021-01-01 00:00:00'
            and  type ='a'
          </select>
          
          //计算页数
          int pageno = total % pagesize == 0 ? total / pagesize : (total / pagesize + 1);
          
          //分页查询,上报
          for(int i = 0; i < pageno; i++){
           list<acctountpo> list = accountdao.listaccountbypage(startrow,pagesize);
           startrow = (pageno-1)*pagesize;
           //上报大数据
           postbigdata(list);
          }
           
          //分页查询sql(可能存在limit深分页问题,因为account表数据量几百万)
          <select id ='listaccountbypage' >
            seelct * 
            from account
            where create_time >='2021-01-01 00:00:00'
            and  type ='a'
            limit #{startrow},#{pagesize}
          </select>
          

          实战优化方案

          以上的实现方案,会存在limit深分页问题,因为account表数据量几百万。那怎么优化呢?

          其实可以使用标签记录法,有些伙伴可能会有疑惑,id主键不是连续的呀,真的可以使用标签记录?

          当然可以,id不是连续,我们可以通过order by让它连续嘛。优化方案如下:

          //查询最小id
          string  lastid = accountdao.queryminid();
          
          //查询最大id对应的sql
          <select id="queryminid" returntype=“java.lang.string”>
          select min(id) 
          from account
          where create_time >='2021-01-01 00:00:00'
          and type ='a'
          </select>
          
          //一页的条数
          integer pagesize = 100;
          
          list<acctountpo> list ;
          do{
             list = listaccountbypage(lastid,pagesize);
             //标签记录法,记录上次查询过的id
             lastid = list.get(list,size()-1).getid();
              //上报大数据
              postbigdata(list);
          }while(collectionutils.isnotempty(list));
          
          <select id ="listaccountbypage">
            select * 
            from account 
            where create_time >='2021-01-01 00:00:00'
            and id > #{lastid}
            and type ='a'
            order by id asc  
            limit #{pagesize}
          </select>
          

          总结

          到此这篇关于mysql深分页问题的文章就介绍到这了,更多相关mysql深分页问题的内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

          (0)
          上一篇 2022年3月21日
          下一篇 2022年3月21日

          相关推荐