MySQL一般使用 LIMIT 实现分页。基本语句为:
SELECT ... FROM ... WHERE ... ORDER BY ... LIMIT ...
在中小数据量的情况下,这样的SQL足够用了,唯一需要注意的问题就是确保使用了索引。
举例来说,如果实际SQL类似下面语句,那么在 category_id, id两列上建立复合索引比较好:
SELECT * FROM articles WHERE category_id = 123 ORDER BY id LIMIT 50, 10 ;
随着数据量的增加,页数会越来越多,查看后几页的SQL就可能类似下面这种:
SELECT * FROM articles WHERE category_id = 123 ORDER BY id LIMIT 10000, 10;
可以看出,越往后分页,LIMIT 语句的偏移量就会越大,速度也会明显变慢。此时,我们可以通过子查询的方式来提高分页效率:
SELECT * FROM articles WHERE id >=
(SELECT id FROM articles WHERE category_id = 123 ORDER BY id LIMIT 10000, 1)
AND category_id = 123 ORDER BY id LIMIT 10;
还可以通过 JOIN 方式来实现分页查询:
SELECT * FROM articles AS t1
JOIN (SELECT id FROM articles WHERE category_id = 123 ORDER BY id LIMIT 10000, 1) AS t2
WHERE t1.id >= t2.id AND t1.category_id = 123 ORDER BY t1.id LIMIT 10;
为什么会这样呢?因为子查询是在索引上完成的,而普通的查询时在数据文件上完成的,通常来说,索引文件要比数据文件小得多,所以操作起来也会更有效率。
实际可以利用类似策略模式的方式去处理分页,比如判断如果是一百页以内,就使用最基本的分页方式,大于一百页,则使用子查询的分页方式。
下面是实际中三种方式的使用:
SELECT * FROM CommodityInfo WHERE commodityid='ZMCOMD342161018143038124' ORDER BY id LIMIT 0,2; SELECT * FROM CommodityInfo WHERE id >=
(SELECT id FROM CommodityInfo WHERE commodityid='ZMCOMD342161018143038124' ORDER BY id LIMIT 0, 1)
AND commodityid='ZMCOMD342161018143038124' ORDER BY id LIMIT 2; SELECT * FROM CommodityInfo AS t1
JOIN (SELECT id FROM CommodityInfo WHERE commodityid = 'ZMCOMD342161018143038124' ORDER BY id LIMIT 0, 1) AS t2
WHERE t1.id >= t2.id AND t1.commodityid='ZMCOMD342161018143038124' ORDER BY t1.id LIMIT 2;