資料庫(SQL)中使用left join後用on還是where,區別大了

前天寫SQL時本想透過 A left B join on and 後面的條件來使查出的兩條記錄變成一條,奈何發現還是有兩條。

後來發現 join on and 不會過濾結果記錄條數,只會根據and後的條件是否顯示 B表的記錄,A表的記錄一定會顯示。

不管and 後面的是A。id=1還是B。id=1,都顯示出A表中所有的記錄,並關聯顯示B中對應A表中id為1的記錄或者B表中id為1的記錄。

執行sql :

select * from student s left join class c on s。classId=c。id order by s。id

資料庫(SQL)中使用left join後用on還是where,區別大了

執行sql :

select * from student s left join class c on s。classId=c。id and s。name=“張三” order by s。id

資料庫(SQL)中使用left join後用on還是where,區別大了

執行sql :

select * from student s left join class c on s。classId=c。id and c。name=“三年級三班” order by s。id

資料庫(SQL)中使用left join後用on還是where,區別大了

資料庫在透過連線兩張或多張表來返回記錄時,都會生成一張中間的臨時表,然後再將這張臨時表返回給使用者。

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

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

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

假設有兩張表:

表1:tab2

id

size

1

10

2

20

3

30

表2:tab2

Size

Name

10

AAA

20

BBB

20

CCC

兩條SQL:

select * form tab1 left join tab2 on (tab1。size = tab2。size) where tab2。name=’AAA’select * form tab1 left join tab2 on (tab1。size = tab2。size and tab2。name=’AAA’)

第一條SQL的過程:

1、中間表on條件:

tab1。size = tab2。size

資料庫(SQL)中使用left join後用on還是where,區別大了

2、再對中間表過濾where 條件:

tab2。name=’AAA’

資料庫(SQL)中使用left join後用on還是where,區別大了

第二條SQL的過程:

1、中間表on條件:

tab1。size = tab2。size and tab2。name=’AAA’

(條件不為真也會返回左表中的記錄)

資料庫(SQL)中使用left join後用on還是where,區別大了

其實以上結果的關鍵原因就是left join,right join,full join的特殊性,不管on上的條件是否為真都會返回left或right表中的記錄,full則具有left和right的特性的並集。

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