SQL中過濾條件放在on和where中的區別

sql中過濾條件放在on和where中的區別,inner join沒區別。後來纔想起來,連接查詢除了inner join還有right join,left join。

join過程可以這樣理解:首先兩個表做一個笛卡爾積,on後面的條件是對這個笛卡爾積做一個過濾形成一張臨時表,如果沒有where就直接返回結果,如果有where就對上一步的臨時表再進行過濾。下面看實驗:

先準備兩張表:


先執行inner join:

select * from person p inner join account a on p.id=a.id and p.id!=4 and a.id!=4;

select * from person p inner join account a on p.id=a.id where p.id!=4 and a.id!=4;

結果沒有區別,前者是先求笛卡爾積然後按照on後面的條件進行過濾,後者是先用on後面的條件過濾,再用where的條件過濾。


再看看左連接left join

select * from person p left join account a on p.id=a.id and p.id!=4 and a.id!=4;

這下看出來不對了,id爲4的記錄還在,這是由left join的特性決定的,使用left join時on後面的條件只對右表有效(可以看到右表的id=4的記錄沒了)

select * from person p left join account a on p.id=a.id where p.id!=4 and a.id!=4;

where的過濾作用就出來了。。。

右連接的原理是一樣的。。


到這裏就真相大白了inner join中on和where沒區別,右連接和左連接就不一樣了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章