SQL中join操作后面的on 和 where 的區別


join關鍵字的作用是將多個表按一定的條件聯合起來,從而可以實現從多個表中獲取數據。
join的常見用法有join、left join 、right join 、full join。

on 和 where 的區別:

on 表示在 join 前進行條件篩選,然后再進行join操作。
where 表示在join操作完了再做過濾。

示例:
現在有兩張表t1 和 t2,表里面的數據如下:

> select * from t1;
+------+------+
| id   | age  |
+------+------+
|    1 |   20 |
|    2 |   21 |
|    3 |   22 |
|    4 |   23 |
|    5 |   24 |
+------+------+

> select * from t2;
+------+------+
| id   | name |
+------+------+
|    1 | Lee  |
|    2 | Bob  |
|    3 | Kate |
|    4 | Tony |
+------+------+

思考一下下面的sql 執行后的結果,有幾條數據:

1)select * from t1 left join t2 on t1.id=t2.id and t1.id=1;
2)select * from t1 left join t2 on t1.id=t2.id and t2.id=1;
3)select * from t1 left join t2 on t1.id=t2.id where t1.id=1;
4)select * from t1 left join t2 on t1.id=t2.id where t2.id=1;

思考5秒鍾......

1 seconds...
2 seconds...
3 seconds...
4 seconds...
5 seconds...

答案是:5、5、1、1

實際輸出結果如下:

1) select * from t1 left join t2 on t1.id=t2.id and t1.id=1;
+------+------+------+------+
| id   | age  | id   | name |
+------+------+------+------+
|    1 |   20 |    1 | Lee  |
|    2 |   21 | NULL | NULL |
|    3 |   22 | NULL | NULL |
|    4 |   23 | NULL | NULL |
|    5 |   24 | NULL | NULL |
+------+------+------+------+

2) select * from t1 left join t2 on t1.id=t2.id and t2.id=1;
+------+------+------+------+
| id   | age  | id   | name |
+------+------+------+------+
|    1 |   20 |    1 | Lee  |
|    2 |   21 | NULL | NULL |
|    3 |   22 | NULL | NULL |
|    4 |   23 | NULL | NULL |
|    5 |   24 | NULL | NULL |
+------+------+------+------+

3) select  * from t1 left join t2 on t1.id=t2.id where t1.id=1;
+------+------+------+------+
| id   | age  | id   | name |
+------+------+------+------+
|    1 |   20 |    1 | Lee  |
+------+------+------+------+

4) select  * from t1 left join t2 on t1.id=t2.id where t2.id=1;
+------+------+------+------+
| id   | age  | id   | name |
+------+------+------+------+
|    1 |   20 |    1 | Lee  |
+------+------+------+------+

注意一點:
left join 時,左表的數據是完整的,on 條件會篩選需要關聯的列,無論能否關聯上,左表都是完整的。比如下面的例子:

> select * from t1 left join t2 on t1.id=t2.id and t2.id=10;
+------+------+------+------+
| id   | age  | id   | name |
+------+------+------+------+
|    1 |   20 | NULL | NULL |
|    2 |   21 | NULL | NULL |
|    3 |   22 | NULL | NULL |
|    4 |   23 | NULL | NULL |
|    5 |   24 | NULL | NULL |
+------+------+------+------+

同理,right join 也是一樣的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM