1. 程式人生 > 其它 >SQL中過濾條件放在on和where中的區別

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

技術標籤:OracleSQL ServerMySQLsql

轉自:https://blog.csdn.net/u013468917/article/details/61933994

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

1. 先執行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的條件過濾。

2.再看看左連線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的過濾作用就出來了。。。

結果的關鍵原因就是left join,right join,full join的特殊性。

不管 on 上的條件是否為真都會返回 left 或 right 表中的記錄,full 則具有 left 和 right 的特性的並集。

而 inner jion 沒這個特殊性,則條件放在 on 中和 where 中,返回的結果集是相同的。