日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

记一个mysql分页查询优化试验

發布時間:2024/9/30 数据库 70 豆豆
生活随笔 收集整理的這篇文章主要介紹了 记一个mysql分页查询优化试验 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題

分頁查詢的時候,如果直接 select 字段1,字段2,...,字段n from 表名 limit offset,pageSize,會隨著offset增大越來越慢。

解決思路

通過查看執行計劃是因為type是all,即全表掃描了,所以思路就是走索引。分頁查詢要求:

  • 數據條數正確
  • 單頁和多頁綜合起來都沒有重復數據

試驗

  • 新建表 product_config,有主鍵。 create table if not exists product_config( configuration_id varchar(50) not null primary key comment "配置模型id,主鍵", product_id varchar(50) not null comment "產品id", product_no varchar(50) not null comment "產品號", product_desc varchar(300) comment "產品描述信息", product_group_id varchar(50) not null comment "產品族id", project_id varchar(30) not null comment "項目id", created_by varchar(50) not null comment "創建此行數據者id", created_time datetime default now() comment "數據入表時間", updated_time datetime default now() comment "數據跟新時間", maintain_by varchar(50) not null comment "此表的維護責任人")ENGINE=InnoDB default charset=utf8;
  • 寫入幾百萬條數據(友情提示,不要手動操作,晚上寫一個定時任務批量往表里寫,睡到第二天就有了,注意的是 mysql 默認一個sql寫入最多寫4M大小,所以每批量不要大于4M)。
  • 全表掃描方式分頁查詢 select configuration_id,product_id,product_no,product_desc,product_group_id,project_id,created_by,created_time,updated_time,maintain_byfrom product_config limit 2000000, 10000;

  • 取執行時間,基本上1000多毫秒,慢,查看執行計劃是全表掃描,不可取。

  • 用走索引的方法

    • 5.1 直接主鍵索引

      select configuration_id,product_id,product_no,product_desc,product_group_id,project_id,created_by,created_time,updated_time,maintain_byfrom product_config where configuration_id > 2000000 order by configuration_id limit 10000;

      不超過500毫秒,看執行計劃只有一步,而且是走的索引,很快,但是因為這種方法是先取出來再排序然后再limit,會漏掉,達不到分頁查詢的要求,不可取

    • 5.2 用主鍵排序再取

      select configuration_id,product_id,product_no,product_desc,product_group_id,project_id,created_by,created_time,updated_time,maintain_byfrom product_config pcwhere pc.configuration_id >= (select configuration_id from product_config order by configuration_id limit 2000000,1) limit 10000;

      比5.1稍慢,比全表掃描的快,看執行計劃分兩步,都是走的索引,數據不重復,不遺漏,推薦

    • 5.3 另一種走索引方式 join

      select pc.configuration_id,pc.product_id,pc.product_no,pc.product_desc,pc.product_group_id,pc.project_id,pc.created_by,pc.created_time,pc.updated_time,pc.maintain_byfrom product_config pcjoin (select configuration_id from product_config order by configuration_id limit 2000000,10000) aon pc.configuration_id = a.configuration_id;

      比5.1和5.2稍慢,看執行計劃分三步,有兩步走了索引,一步全表掃描(但是掃的時查出來的數據了),可取

    總結

    以上是生活随笔為你收集整理的记一个mysql分页查询优化试验的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。