准备工作
-
表名:order_history -
描述:某个业务的订单历史表 -
主要字段:unsigned int id,tinyint(4) int type -
字段情况:该表一共37个字段,不包含text等大型数据,最大为varchar(500),id字段为索引,且为递增。 -
数据量:5709294 -
MySQL版本:5.7.16 线下找一张百万级的测试表可不容易,如果需要自己测试的话,可以写shell脚本什么的插入数据进行测试。以下的 sql 所有语句执行的环境没有发生改变,下面是基本测试结果:
-
8903 ms -
8323 ms -
8401 ms
一般分页查询
-
第一个参数指定第一个返回记录行的偏移量,注意从 0
开始 -
第二个参数指定返回记录行的最大数目 -
如果只给定一个参数:它表示返回最大的记录行数目 -
第二个参数为 -1 表示检索从某一个偏移量到记录集的结束所有的记录行 -
初始记录行的偏移量是 0(而不是 1)
offset: 1000
开始之后的10条数据,也就是第1001条到第1010条数据(1001 <= id <= 1010
)。-
3040 ms -
3063 ms -
3018 ms
select * from orders_history where type=8 limit 10000,10;
select * from orders_history where type=8 limit 10000,100;
select * from orders_history where type=8 limit 10000,1000;
select * from orders_history where type=8 limit 10000,10000;
-
查询1条记录:3072ms 3092ms 3002ms -
查询10条记录:3081ms 3077ms 3032ms -
查询100条记录:3118ms 3200ms 3128ms -
查询1000条记录:3412ms 3468ms 3394ms -
查询10000条记录:3749ms 3802ms 3696ms
select * from orders_history where type=8 limit 1000,100;
select * from orders_history where type=8 limit 10000,100;
select * from orders_history where type=8 limit 100000,100;
select * from orders_history where type=8 limit 1000000,100;
-
查询100偏移:25ms 24ms 24ms -
查询1000偏移:78ms 76ms 77ms -
查询10000偏移:3092ms 3212ms 3128ms -
查询100000偏移:3878ms 3812ms 3798ms -
查询1000000偏移:14608ms 14062ms 14700ms
使用子查询优化
select id from orders_history where type=8 limit 100000,1;
select * from orders_history where type=8 and
id>=(select id from orders_history where type=8 limit 100000,1)
limit 100;
select * from orders_history where type=8 limit 100000,100;
-
第1条语句:3674ms -
第2条语句:1315ms -
第3条语句:1327ms -
第4条语句:3710ms
-
比较第1条语句和第2条语句:使用 select id 代替 select * 速度增加了3倍 -
比较第2条语句和第3条语句:速度相差几十毫秒 -
比较第3条语句和第4条语句:得益于 select id 速度增加,第3条语句查询速度增加了3倍
使用 id 限定优化
and id between 1000000 and 1000100 limit 100;
(select order_id from trade_2 where goods = ‘pen’)
limit 100;
使用临时表优化
关于数据表的id说明
未经允许不得转载:大自然的搬运工 » 面试:数据量很大,分页查询很慢,有什么优化方案?