溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

MySQL5.7中如何進(jìn)行優(yōu)化union all

發(fā)布時(shí)間:2021-11-16 09:22:19 來(lái)源:億速云 閱讀:1292 作者:柒染 欄目:MySQL數(shù)據(jù)庫(kù)

MySQL5.7中如何進(jìn)行優(yōu)化union all,相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

 MySQL5.6中,使用union all相當(dāng)于創(chuàng)建一張臨時(shí)表,這在執(zhí)行大的聯(lián)合查詢時(shí)候會(huì)增加I/O開銷,降低查詢速度。
 例如執(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)擊(此處)折疊或打開

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 | <union1,2> | ALL | NULL | NULL | NULL | NULL | NULL | Using temporary |

 可以看到執(zhí)行計(jì)劃中提現(xiàn)到了創(chuàng)建的臨時(shí)表。
 在MySQL5.7環(huán)境:
點(diǎn)擊(此處)折疊或打開

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è)查詢過程沒有創(chuàng)建臨時(shí)表,按照順序,accessLog表的查詢結(jié)果首先傳輸?shù)娇蛻舳?,然后access_test表的查詢結(jié)果再傳輸?shù)娇蛻舳恕?br/> 注意:此項(xiàng)優(yōu)化對(duì)union和在最外層用order by無(wú)效,如下:
點(diǎn)擊(此處)折疊或打開

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 | <union1,2> | NULL | ALL | NULL | NULL | NULL | NULL | NULL | NULL | Using temporary; Using filesort |

看完上述內(nèi)容,你們掌握MySQL5.7中如何進(jìn)行優(yōu)化union all的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI