Mysql的Join語句中On和Where條件的區別
首先創建兩張測試用表
create table t1 (id int not null,c1 int,primary key(id))
create table t2 like t1
插入如下的數據
t1
id | c1 |
---|---|
1 | 10 |
2 | 20 |
3 | 30 |
t2
id | c1 |
---|---|
1 | 10 |
2 | 40 |
3 | 50 |
執行以下的兩條語句
1.條件在on後面
select * from t1 left join t2 on t1.id=t2.id and t1.c1=t2.c1
結果如下:
id | c1 | id | c2 |
---|---|---|---|
1 | 10 | 1 | 10 |
2 | 20 | NULL | NULL |
3 | 30 | NULL | NULL |
2.條件在where後面
select * from t1 left join t2 on t1.id=t2.id where t1.c1=t2.c1
結果如下:
id | c1 | id | c2 |
---|---|---|---|
1 | 10 | 1 | 10 |
結論:
left join中(right join同理)跟在on後面的條件並不會過濾左表,最終的結果一定包括左表的數據,但是會過濾右表的數據。而where後的條件,是在join的結果後進行過濾。