点击上方“
朱小厮的博客
”,选择“
设为星标
”
做积极的人,而不是积极废人
来源:
http://uee.me/aVSnD
当需要从数据库查询的表有上万条记录的时候,一次性查询所有结果会变得很慢,特别是随着数据量的增加特别明显,这时需要使用分页查询。对于数据库分页查询,也有很多种方法和优化的点。
下面简单说一下我知道的一些方法。
准备工作
为了对下面列举的一些优化进行测试,下面针对已有的一张表进行说明。
-
表名:order_history
-
描述:某个业务的订单历史表
-
主要字段:unsigned int id,tinyint(4) int type
-
字段情况:该表一共37个字段,不包含text等大型数据,最大为varchar(500),id字段为索引,且为递增。
-
数据量:5709294
-
MySQL版本:5.7.16 线下找一张百万级的测试表可不容易,如果需要自己测试的话,可以写shell脚本什么的插入数据进行测试。 以下的 sql 所有语句执行的环境没有发生改变,下面是基本测试结果:
select count(*) from orders_history;
返回结果:5709294
三次查询时间分别为:
一般分页查询
一般的分页查询使用简单的 limit 子句就可以实现。limit 子句声明如下:
SELECT * FROM table LIMIT [offset,] rows | rows OFFSET offset
LIMIT 子句可以被用于指定 SELECT 语句返回的记录数。需注意以下几点:
下面是一个应用实例:
select * from orders_history where type=8 limit 1000,10;
该条语句将会从表 orders_history 中查询
offset:1000
开始之后的10条数据,也就是第1001条到第1010条数据(
1001<=id<=1010
)。
数据表中的记录默认使用主键(一般为id)排序,上面的结果相当于:
select * from orders_history where type=8 order by id limit 10000,10;
三次查询时间分别为:
针对这种查询方式,下面测试查询记录量对时间的影响:
select * from orders_history where type=8 limit 10000,1;
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
另外我还做了十来次查询,从查询时间来看,基本可以确定,在查询记录量低于100时,查询时间基本没有差距,随着查询记录量越来越大,所花费的时间也会越来越多。
针对查询偏移量的测试:
select * from orders_history where type=8 limit 100,100;
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
随着查询偏移的增大,尤其查询偏移大于10万以后,查询时间急剧增加。
这种分页查询方式会从数据库第一条记录开始扫描,所以越往后,查询速度越慢,而且查询的数据越多,也会拖慢总查询速度。
使用子查询优化
这种方式先定位偏移位置的 id,然后往后查询,这种方式适用于 id 递增的情况。
select * from orders_history where type=8 limit 100000,1;
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;
4条语句的查询时间如下:
-
第1条语句:3674ms
-
第2条语句:1315ms
-
第3条语句:1327ms
-
第4条语句:3710ms
针对上面的查询需要注意: