2016-05-11 196 views
0

我試圖用一些條件創建一個左連接查詢,但它似乎很奇怪。左連接條件不影響結果

SELECT c.country_id, c.country_name, IFNULL(MAX(b.bid_amount),0) 
FROM countries AS c 
LEFT JOIN items_bids AS b 
ON c.country_id = b.bid_country_id 
AND b.bid_removed = 0 
LEFT JOIN advertisers AS a 
ON a.advertiser_id = b.bid_advertiser_id 
AND a.advertiser_balance > 0 
AND a.advertiser_review = 0 
LEFT JOIN items AS n 
ON b.bid_item_id = n.item_id 
AND n.item_approved = 1 
AND n.item_deleted = 0 
AND n.item_paused = 0 
GROUP BY c.country_name 

它具有相同的結果,因爲這:它沒有被任何的ON子句條件採取行動

SELECT c.country_id, c.country_name, IFNULL(MAX(b.bid_amount),0) 
FROM countries AS c 
LEFT JOIN items_bids AS b 
ON c.country_id = b.bid_country_id 
LEFT JOIN advertisers AS a 
ON a.advertiser_id = b.bid_advertiser_id 
LEFT JOIN items AS n 
ON b.bid_item_id = n.item_id 
GROUP BY c.country_name 

我敢肯定,這應該是一個不同的結果,因爲如果我把這些條件放在WHERE子句中,而不是ON子句,它確實有效。

問題是,我正在使用LEFT JOIN,因爲我不想從結果中消除任何國家。

+1

您可以包括與預期結果數據的小樣本? –

回答

0

您的on-條件不按預期工作,因爲您使用left join連接表,然後從不使用它們,因此它們不起作用。您只使用max(b.bid_amount)countries,因此只有在bcountries的條件纔會生效。

例如,如果某些行的advertisers存在即滿足您的on -condition,它們結合,但對b.bid_amount沒有影響,因爲你不使用它們(他們會對例如count(*)sum(b.bid_amount)效果雖然)。如果advertisers沒有行,則由於left join,它們對b.bid_amount也沒有影響。所以你的條件是什麼並不重要。

你的第一個代碼就相當於

SELECT c.country_id, c.country_name, IFNULL(MAX(b.bid_amount),0) 
FROM countries AS c 
LEFT JOIN items_bids AS b 
ON c.country_id = b.bid_country_id 
AND b.bid_removed = 0 
GROUP BY c.country_name 

和你的第二個代碼相當於

SELECT c.country_id, c.country_name, IFNULL(MAX(b.bid_amount),0) 
FROM countries AS c 
LEFT JOIN items_bids AS b 
ON c.country_id = b.bid_country_id 
GROUP BY c.country_name 

,它可能不是奇怪,他們給出相同的結果(取決於 您的數據和有多少行b.bid_removed = 0。嘗試b.bid_removed = 1,你可能會看到一個效果,這是唯一相關的條件)。

如果你把你的條件,例如條款中的AND a.advertiser_balance > 0,mysql只會選擇a.advertiser_balance不爲空的行!所以你的left join將作爲join,並不奇怪,這可能會有不同的結果。

由於您沒有描述您實際想要達到的目標,我會大膽猜測並刪除一些左連接。您將獲得所有國家,並且您的所有on條件都可以使用。

嘗試

SELECT c.country_id, c.country_name, IFNULL(MAX(b.bid_amount),0) 
FROM countries AS c 
LEFT JOIN items_bids AS b 
ON c.country_id = b.bid_country_id 
AND b.bid_removed = 0 
JOIN advertisers AS a 
ON a.advertiser_id = b.bid_advertiser_id 
AND a.advertiser_balance > 0 
AND a.advertiser_review = 0 
JOIN items AS n 
ON b.bid_item_id = n.item_id 
AND n.item_approved = 1 
AND n.item_deleted = 0 
AND n.item_paused = 0 
GROUP BY c.country_name