企业如何通过vue小程序开发满足高效运营与合规性需求
238
2023-12-26
如何进行SQL优化中的limit分页优化,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
示例表aaaaa中共有2375690数据。
优化前的SQL
SQL执行结果:
SELECT DISTINCT(device_id) uid FROM aaaaa WHERE status = 0 LIMIT 88000,1000; 1000 rows inset (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 fromstar_device_5limit 880000,1) k on star_device_5.id>=k.id where status=0 limit 1000; 1000 rows in set (0.19sec)随着m的增大和n的增大,两种写法的SQL执行时间会有本质差别。我做了测试,当m值增加到880000时,优化前的SQL需要2分钟,优化后的SQL还是0.1s左右。
看完上述内容,你们掌握如何进行SQL优化中的limit分页优化的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~