MySQL5.7中如何進(jìn)行優(yōu)化union all,相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
站在用戶(hù)的角度思考問(wèn)題,與客戶(hù)深入溝通,找到公主嶺網(wǎng)站設(shè)計(jì)與公主嶺網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個(gè)性化、用戶(hù)體驗(yàn)好的作品,建站類(lèi)型包括:網(wǎng)站設(shè)計(jì)制作、成都網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、主機(jī)域名、雅安服務(wù)器托管、企業(yè)郵箱。業(yè)務(wù)覆蓋公主嶺地區(qū)。
MySQL5.6中,使用union all相當(dāng)于創(chuàng)建一張臨時(shí)表,這在執(zhí)行大的聯(lián)合查詢(xún)時(shí)候會(huì)增加I/O開(kāi)銷(xiāo),降低查詢(xún)速度。
例如執(zhí)行以下SQL語(yǔ)句:
(select id from accessLog order by id) union all (select id from access_test order by id);
在MySQL5.6環(huán)境:
點(diǎn)擊(此處)折疊或打開(kāi)
mysql> select version();
| version() |
| 5.6.14-log |
1 row in set (0.00 sec)
mysql> explain (select id from accessLog order by id) union all (select id from access_test order by id);
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
| 1 | PRIMARY | accessLog | index | NULL | loginuserId | 9 | NULL | 535513 | Using index |
| 2 | UNION | access_test | index | NULL | idx_loginuid | 9 | NULL | 477248 | Using index |
| NULL | UNION RESULT |
可以看到執(zhí)行計(jì)劃中提現(xiàn)到了創(chuàng)建的臨時(shí)表。
在MySQL5.7環(huán)境:
點(diǎn)擊(此處)折疊或打開(kāi)
mysql> select version();
| version() |
| 5.7.18-log |
1 row in set (0.00 sec)
mysql> explain (select id from accessLog order by id) union all (select id from access_test order by id);
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
| 1 | PRIMARY | accessLog | NULL | index | NULL | loginuserId | 9 | NULL | 586090 | 100.00 | Using index |
| 2 | UNION | access_test | NULL | ALL | NULL | NULL | NULL | NULL | 571023 | 100.00 | NULL |
整個(gè)查詢(xún)過(guò)程沒(méi)有創(chuàng)建臨時(shí)表,按照順序,accessLog表的查詢(xún)結(jié)果首先傳輸?shù)娇蛻?hù)端,然后access_test表的查詢(xún)結(jié)果再傳輸?shù)娇蛻?hù)端。
注意:此項(xiàng)優(yōu)化對(duì)union和在最外層用order by無(wú)效,如下:
點(diǎn)擊(此處)折疊或打開(kāi)
mysql> select version();
| version() |
| 5.7.18-log |
1 row in set (0.00 sec)
mysql> explain (select id from accessLog order by id) union all (select id from access_test order by id) order by id;
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
| 1 | PRIMARY | accessLog | NULL | index | NULL | loginuserId | 9 | NULL | 586090 | 100.00 | Using index |
| 2 | UNION | access_test | NULL | ALL | NULL | NULL | NULL | NULL | 571023 | 100.00 | NULL |
| NULL | UNION RESULT |
看完上述內(nèi)容,你們掌握MySQL5.7中如何進(jìn)行優(yōu)化union all的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!