如何進(jìn)行SQL優(yōu)化中的limit分頁優(yōu)化,相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
蕪湖縣網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)公司!從網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站設(shè)計(jì)等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營維護(hù)。創(chuàng)新互聯(lián)公司2013年開創(chuàng)至今到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)公司。
表aaaaa中共有2375690數(shù)據(jù)。
優(yōu)化前的SQL
SQL執(zhí)行結(jié)果:
SELECT DISTINCT(device_id) uid FROM aaaaa WHERE status = 0 LIMIT 88000,1000; 1000 rows in set (0.48 sec)
SQL執(zhí)行計(jì)劃:
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 | +------+-------------+---------------+------+---------------+------+---------+------+---------+------------------------------+
優(yōu)化方式
迅速定位起始ID,利用主鍵索引,加快掃描速度。可以看到,derived中,SQL使用到了覆蓋索引進(jìn)行掃描,雖然還是全表掃,因?yàn)橹粧呙鑙d列,大大降低了掃描的IO耗費(fèi),快速定位到了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 | +------+-------------+---------------+-------+---------------+-------------+---------+------+---------+------------------------------------------------+
執(zhí)行結(jié)果:
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執(zhí)行時(shí)間會(huì)有本質(zhì)差別。我做了測試,當(dāng)m值增加到880000時(shí),優(yōu)化前的SQL需要2分鐘,優(yōu)化后的SQL還是0.1s左右。
看完上述內(nèi)容,你們掌握如何進(jìn)行SQL優(yōu)化中的limit分頁優(yōu)化的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!