共計 2354 個字符,預計需要花費 6 分鐘才能閱讀完成。
這期內容當中丸趣 TV 小編將會給大家帶來有關 MySQL not in 嵌套查詢如何改寫成外連接方式,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
在 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)
上述就是丸趣 TV 小編為大家分享的 MySQL not in 嵌套查詢如何改寫成外連接方式了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注丸趣 TV 行業資訊頻道。