JOIN 和 WHERE?簡單的問題也有學問。

來源:互聯網
上載者:User

今天在寫SQL語句時,忽然想瞭解下 JOIN 和 WHERE 之間的順序。簡單的說,到底是先關聯出資料再篩選,還是先篩選資料再關聯。

理論上來說,應該是 先 JOIN 出資料然後再 WHERE。忍不住到發帖詢問了下,牛人給出了精闢的答案,不敢苟藏:

 

 

/*

標題:SQL中on條件與where條件的區別

作者:愛新覺羅·毓華

時間:2008-07-14

地點:新疆烏魯木齊

*/

 

資料庫在通過串連兩張或多張表來返回記錄時,都會產生一張中間的暫存資料表,然後再將這張暫存資料表返回給使用者。

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

 

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

 

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

 

假設有兩張表:

 

表1:tab1

id size

1  10

2  20

3  30

表2:tab2

size name

10  AAA

20  BBB

20  CCC

 

兩條SQL:

1、select * from tab1left join tab2 on tab1.size = tab2.size where tab2.name='AAA'

2、select * from tab1left join tab2 on tab1.size = tab2.size and tab2.name='AAA'

 

第一條SQL的過程:

1、中間表

on條件:

tab1.size = tab2.size

tab1.id tab1.size tab2.size tab2.name

1 10 10 AAA

2 20 20 BBB

2 20 20 CCC

3 30 (null) (null)

2、再對中間表過濾

where 條件:

tab2.name='AAA'

tab1.id tab1.size tab2.size tab2.name

1 10 10 AAA

 

第二條SQL的過程:

1、中間表

on條件:

tab1.size = tab2.size and tab2.name='AAA'

(條件不為真也會返回左表中的記錄)tab1.id tab1.size tab2.size tab2.name

1 10 10 AAA

2 20 (null) (null)

3 30 (null) (null)

 

其實以上結果的關鍵原因就是left join,right join,full join的特殊性,

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

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.