MySQL not in巢狀查詢改寫成外連線方式

feelpurple發表於2016-08-18

在MySQL中,not in 巢狀查詢會在資料庫裡面建立一張臨時表,導致執行效率很低,可以改成外連線的方式處理,效率會好很多。

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)

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26506993/viewspace-2123663/,如需轉載,請註明出處,否則將追究法律責任。

相關文章