您好,登錄后才能下訂單哦!
如何進行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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。