left join on +多條件與where區別
重點
先匹配,再篩選where條件。
本文將通過幾個例子說明兩者的差別。
表1:product
id | amount |
---|---|
1 | 100 |
2 | 200 |
3 | 300 |
4 | 400 |
表2:product_details
id | weight | exist |
---|---|---|
2 | 22 | 0 |
4 | 44 | 1 |
5 | 55 | 0 |
6 | 66 | 1 |
1. 單個條件
select * from product a
left join product_details b
on a.id = b.id
以左表為准匹配,結果:
id | amount | id | weight | exist |
---|---|---|---|---|
1 | 100 | null | null | null |
2 | 200 | 2 | 22 | 0 |
3 | 300 | null | null | null |
4 | 400 | 4 | 44 | 1 |
2. 條件寫在on 與where區別
查詢1:
SELECT * FROM product LEFT JOIN product_details
ON (product.id = product_details.id)
AND product.amount=200;
結果:
id | amount | id | weight | exist |
---|---|---|---|---|
1 | 100 | null | null | null |
2 | 200 | 2 | 22 | 0 |
3 | 300 | null | null | null |
4 | 400 | null | null | null |
把on的所有條件作為匹配條件,不符合的右表都為null。
查詢2:
SELECT * FROM product LEFT JOIN product_details
ON (product.id = product_details.id)
WHERE product.amount=200;
id | amount | id | weight | exist |
---|---|---|---|---|
2 | 200 | 2 | 22 | 0 |
匹配完再篩選,結果只有一條記錄。
3. where XXX is null 情況
使用該語句表示:刪除掉不匹配on后面條件的記錄。
where XXX is not null 則表示篩選出符合on后面條件的記錄。
常用於只需要左表的數據,比如count id這類。
SELECT a.* FROM product a LEFT JOIN product_details b
ON a.id=b.id AND b.weight!=44 AND b.exist=0
WHERE b.id IS NULL;
結果:
id | amount |
---|---|
1 | 100 |
3 | 300 |
4 | 400 |
可以直觀看出,只有id=2的紀錄完全匹配上三個條件,所以篩除這條紀錄,另三條保留,此時這三條紀錄的右表均為null。
篩選出不符合on后面條件的,即 !(a.id=b.id AND b.weight!=44 AND b.exist=0).
!(a.id=b.id AND || !(b.weight!=44) || !(b.exist=0).
(a.id != b.id AND || (b.weight = 44) || ( b.exist! = 0).
邏輯 AND 和 邏輯 OR表達式,其操作數是從左到右求值的。如果第一個參數做夠判斷操作結果,那么第二個參數便不會被計算求值(短路效果)。
下面語句與該語句效果相同:(這里相同指的是最后只用到左表數據,若是將右表數據寫出來是不一樣的)
SELECT a.* FROM product a LEFT JOIN product_details b
ON a.id=b.id
WHERE b.id is null OR b.weight=44 OR b.exist=1;
將on的否定條件寫在where后,效果相同。
注:
如果你使用 LEFT JOIN 來尋找在一些表中不存在的記錄,你需要做下面的測試:WHERE 部分的 col_name IS NULL,MYSQL 在查詢到一條匹配 LEFT JOIN 條件后將停止搜索更多行(在一個特定的組合鍵下)。