1. 程式人生 > 實用技巧 >sql join 和 left join 區別 on 和 where 區別

sql join 和 left join 區別 on 和 where 區別

有三張表
film

category

film_category

left join 查詢結果

select *
from film f left join film_category fc on f.film_id=fc.f_id

select *
from film f left join film_category fc on f.film_id=fc.f_id
where fc.c_id is null

select *
from film f left join film_category fc on f.film_id=fc.f_id
and fc.c_id is null

join查詢結果

select *
from film f join film_category fc on f.film_id=fc.f_id

select *
from film f join film_category fc on f.film_id=fc.f_id
where fc.c_id is null

select *
from film f join film_category fc on f.film_id=fc.f_id
and fc.c_id is null

結論:

1.join 的where 和on沒有區別,內連結,只有複核條件的才會顯示出來,條件加在那裡都可以

2.left join 的where和on有區別,left join 不管on的條件是否匹配都是顯示左表的全部內容,然後形成虛擬表,通過where去篩選臨時表中滿足條件的記錄

如果篩選條件在on就會造成匹配不到的資料,左側還是左表的內容,右邊全是null而忽略連結條件

left join 篩選的主要是右表,如果篩選不到就會在臨時表中顯示null,這裡on加的是連結條件,篩選條件在where中

where不能放函式,函式條件需要放在having中