温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

MySQL5.7中如何进行优化union all

发布时间:2021-11-16 09:22:19 来源:亿速云 阅读:1265 作者:柒染 栏目:MySQL数据库

MySQL5.7中如何进行优化union all,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

 MySQL5.6中,使用union all相当于创建一张临时表,这在执行大的联合查询时候会增加I/O开销,降低查询速度。
 例如执行以下SQL语句:
 (select id from accessLog order by id) union all (select id from access_test order by id);
 在MySQL5.6环境:

点击(此处)折叠或打开

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 |

 可以看到执行计划中提现到了创建的临时表。
 在MySQL5.7环境:
点击(此处)折叠或打开

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 |

  整个查询过程没有创建临时表,按照顺序,accessLog表的查询结果首先传输到客户端,然后access_test表的查询结果再传输到客户端。
 注意:此项优化对union和在最外层用order by无效,如下:
点击(此处)折叠或打开

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 |

看完上述内容,你们掌握MySQL5.7中如何进行优化union all的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI