您好,登录后才能下订单哦!
这期内容当中小编将会给大家带来有关MySQL not in嵌套查询如何改写成外连接方式,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
在MySQL中,not in 嵌套查询会在数据库里面创建一张临时表,导致执行效率很低,可以改成外连接的方式处理,效率会好很多。
mysql> select * from dept where deptno not in (select deptno from emp);
+--------+------------+---------+
| deptno | dname | loc |
+--------+------------+---------+
| 40 | OPERATIONS | BOSTON |
| 50 | Research | BeiJing |
+--------+------------+---------+
2 rows in set (0.00 sec)
mysql> explain select * from dept where deptno not in (select deptno from emp);
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| 1 | PRIMARY | dept | ALL | NULL | NULL | NULL | NULL | 5 | Using where |
| 2 | SUBQUERY | emp | ALL | NULL | NULL | NULL | NULL | 14 | NULL |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
2 rows in set (0.00 sec)
mysql> select * from dept e left join emp d on e.deptno=d.deptno where d.deptno is null;
+--------+------------+---------+-------+-------+------+------+----------+------+------+--------+
| deptno | dname | loc | empno | ename | job | mgr | hiredate | sal | com | deptno |
+--------+------------+---------+-------+-------+------+------+----------+------+------+--------+
| 40 | OPERATIONS | BOSTON | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| 50 | Research | BeiJing | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
+--------+------------+---------+-------+-------+------+------+----------+------+------+--------+
2 rows in set (0.00 sec)
mysql> explain select * from dept e left join emp d on e.deptno=d.deptno where d.deptno is null;
+----+-------------+-------+------+---------------+------+---------+------+------+----------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+----------------------------------------------------+
| 1 | SIMPLE | e | ALL | NULL | NULL | NULL | NULL | 5 | NULL |
| 1 | SIMPLE | d | ALL | NULL | NULL | NULL | NULL | 14 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+------+---------------+------+---------+------+------+----------------------------------------------------+
2 rows in set (0.00 sec)
上述就是小编为大家分享的MySQL not in嵌套查询如何改写成外连接方式了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。