mysql 翻页优化

mysql翻页优化

对于翻页,我们通常是用

select fields from table limit 100,10

但是当要越翻后面的页数之后,耗时变得很长

select fields from table limit 1000000,10

explain select * from `user`  where id >=  (select id from `user` limit 10000000, 1)  limit 10

究其原因,是因为mysql在查询中,查询了1000010条数据,并把前面的1000000数据给丢掉了。以下是该查询的explain

MySQL [test]> explain select * from `user` limit 1000000,10;
+----+-------------+-------+------------+------+---------------+------+---------+------+----------+----------+-------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows     | filtered | Extra |
+----+-------------+-------+------------+------+---------------+------+---------+------+----------+----------+-------+
|  1 | SIMPLE      | user  | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 15053672 |   100.00 | NULL  |
+----+-------------+-------+------------+------+---------------+------+---------+------+----------+----------+-------+
1 row in set, 1 warning (0.00 sec)

解决方案

方案一

不给查页数过大的数据,例如百度搜索的结果,最大页数在100页以内。但是这个只适用部分场景

方案二

优化sql,让mysql在主键索引上进行limit
此sql在数据量百万内基本是在1s内完成,当数据量上去之后,则耗时更久

select * from user where id in (select tmp.id from ( select id from `user` order by id asc  limit 1000010,10 ) as tmp )

方案三

进行模糊查找
这个速度是最快的,而且不管数据量的大小,都在毫秒级
缺点是无法完成条件搜索

select * from user where id >1000000 limit 10 
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容