您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
如何进行SQL优化中的limit分页优化,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
表aaaaa中共有2375690数据。
优化前的SQL
SQL执行结果:
SELECT DISTINCT(device_id) uid FROM aaaaa WHERE status = 0 LIMIT 88000,1000; 1000 rows in set (0.48 sec)
SQL执行计划:
MariaDB [star]> explain SELECT sql_no_cache DISTINCT(device_id) uid FROM aaaaa WHERE status = 0 LIMIT 88000,1000; +------+-------------+---------------+------+---------------+------+---------+------+---------+------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +------+-------------+---------------+------+---------------+------+---------+------+---------+------------------------------+ | 1 | SIMPLE | aaaaa | ALL | NULL | NULL | NULL | NULL | 2375690 | Using where; Using temporary | +------+-------------+---------------+------+---------------+------+---------+------+---------+------------------------------+
优化方式
迅速定位起始ID,利用主键索引,加快扫描速度。可以看到,derived中,SQL使用到了覆盖索引进行扫描,虽然还是全表扫,因为只扫描id列,大大降低了扫描的IO耗费,快速定位到了id。
MariaDB [star]> explain SELECT sql_no_cache DISTINCT(device_id) uid FROM aaaaa join (select id from aaaaa limit 88000,1) k on star_device_5.id>=k.id where status=0 limit 1000; +------+-------------+---------------+-------+---------------+-------------+---------+------+---------+------------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +------+-------------+---------------+-------+---------------+-------------+---------+------+---------+------------------------------------------------+ | 1 | PRIMARY | | ALL | NULL | NULL | NULL | NULL | 88001 | Using temporary | | 1 | PRIMARY | star_device_5 | ALL | PRIMARY | NULL | NULL | NULL | 2377112 | Range checked for each record (index map: 0x1) | | 2 | DERIVED | star_device_5 | index | NULL | idx_star_id | 8 | NULL | 2377112 | Using index | +------+-------------+---------------+-------+---------------+-------------+---------+------+---------+------------------------------------------------+
执行结果:
SELECT sql_no_cache DISTINCT(device_id) uid FROM star_device_5 join (select id from star_device_5 limit 880000,1) k on star_device_5.id>=k.id where status=0 limit 1000; 1000 rows in set (0.19 sec)
随着m的增大和n的增大,两种写法的SQL执行时间会有本质差别。我做了测试,当m值增加到880000时,优化前的SQL需要2分钟,优化后的SQL还是0.1s左右。
看完上述内容,你们掌握如何进行SQL优化中的limit分页优化的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。