优化mysql的limit offset的例子
经常碰到的一个问题是limit的offset太高,如:limit 100000,20,这样系统会查询100020条,然后把前面的100000条都扔掉,这是开销很大的操作,导致查询很慢。假设所有分页的页面访问频率一
经常碰到的一个问题是limit的offset太高,如:limit 100000,20,这样系统会查询100020条,然后把前面的100000条都扔掉,这是开销很大的操作,导致查询很慢。假设所有分页的页面访问频率一样,这样的查询平均扫描表的一半数据。优化的方法,要么限制访问后面的页数,要么提升高偏移的查询效率。
一个简单的优化办法是使用覆盖查询(covering index)查询,然后再跟全行的做join操作。如:复制代码 代码如下:SQL>select * from user_order_info limit 1000000,5;这条语句就可以优化为:复制代码 代码如下:select * from user_order_info inner join (select pin from user_order_info limit 1000000,5) as lim using(pin);SQL>explain select * from user_order_info limit 1000000,5;+----+-------------+-----------------+------+---------------+------+---------+------+----------+-------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |+----+-------------+-----------------+------+---------------+------+---------+------+----------+-------+| 1 | SIMPLE | user_order_info | ALL | NULL | NULL | NULL | NULL | 23131886 | |+----+-------------+-----------------+------+---------------+------+---------+------+----------+-------+1 row in set (0.00 sec)SQL>explain extended select * from user_order_info inner join (select pin from user_order_info limit 1000000,5) as lim using(pin);+----+-------------+-----------------+--------+---------------+---------+---------+---------+----------+----------+-------------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |+----+-------------+-----------------+--------+---------------+---------+---------+---------+----------+----------+-------------+| 1 | PRIMARY |