在join中,on和where的區別


兩個表在,join時,首先做一個笛卡爾積,on后面的條件是對這個笛卡爾積做一個過濾形成一張臨時表,如果沒有where就直接返回結果,如果有where就對上一步的臨時表再進行過濾。

在使用left  jion時,on和where條件的區別如下:

1、on條件是在生成臨時表時使用的條件,它不管on中的條件是否為真,都會返回左邊表中的記錄。

2、where條件是在臨時表生成好后,再對臨時表進行過濾的條件。這時已經沒有left  join的含義(必須返回左邊表的記錄)了,條件不為真的就全部過濾掉

先准備兩張表:

 

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;

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

在on為選擇條件時,id為4的記錄還在,這是由left join的特性決定的,使用left join時on后面的條件只對右表有效(可以看到右表的id=4的記錄為NULL)

在where為選擇條件時,where過濾掉了左表中的內容。

 

原文:

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

https://www.cnblogs.com/guanshan/articles/guan062.html

https://blog.csdn.net/qq_34778597/article/details/82967016


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM