left join 過濾條件寫在on後面和寫在where 後面的區別
create table t1(id int, feild int);
insert into t1 values(1 , 1);
insert into t1 values(1 , 2);
insert into t1 values(1 , 3);
insert into t1 values(1 , 4);
insert into t1 values(2 , 1);
insert into t1 values(2 , 2);
create table t2(id int, feild int);
insert into t2 values(1 , 1);
insert into t2 values(1 , 2);
insert into t2 values(1 , 5);
insert into t2 values(1 , 6);
insert into t2 values(2 , 1);
insert into t2 values(2 , 3);
select t1.*,t2.* from t1 left join t2 on t1.id=t2.id
--取t1表的第一行,掃瞄t2表,按條件做對比,如果滿足條件,就加入返回結果表.
然後取t1表的第二行,掃瞄t2表,按條件做對比,如果滿足條件,就加入返回結果表.
重複以上過程,直到t1表掃描結束.
select t1.*,t2.* from t1 left join t2 on t1.id=t2.id and t1.feild=1
--給左表加條件的時候,左表滿足條件的,按上面的過程返回值,左表不滿足條件的,直接輸出,右表的列補null
1 1 1 1
1 1 1 2
1 1 1 5
1 1 1 6
2 1 2 1
2 1 2 3
1 2 NULL NULL
1 3 NULL NULL
1 4 NULL NULL
2 2 NULL NULL
select t1.*,t2.* from t1 left join t2 on t1.id=t2.id where t1.feild=1 先執行where後連線查詢
執行where後表為 1 , 1
2 , 1
用它來left join t2.
--下面三條語句查詢結果是一樣的,當為右表加條件的時候,可以把left join 改為inner jin, 因為inner join比left join 要快!
select t1.*,t2.* from t1 left join t2 on t1.id=t2.id and t2.feild=1
select t1.*,t2.* from t1 left join t2 on t1.id=t2.id where t2.feild=1
select t1.*,t2.* from t1 inner join t2 on t1.id=t2.id and t2.feild=1
更多詳情請點選:更多介紹