2011-10-06 74 views
0

我知道有很多很好的問題在左回答回答,但我有麻煩找到有關我的特定問題的東西。我爲可能重複的話題表示歉意,但不勝感激。MySQL左加入不產生預期結果

我有兩個包含禮品卡銷售的表。我必須驗證金額是否匹配。 我正在尋找幫助編寫一個查詢,從表一回一切即使是表B.不匹配的記錄

表A

| id | business_date | am_pm | gift_cards_sold | 
================================================ 
103 | 2011-10-06 | PM | 175.03 
104 | 2011-10-06 | PM | 135.03 
105 | 2011-10-06 | PM | 250.74 
106 | 2011-10-06 | PM | 180.44 
107 | 2011-10-06 | PM | 150.10 
108 | 2011-10-06 | PM | 130.00 

表B

| id | business_date | am_pm | gift_cards_sold | 
================================================ 
103 | 2011-10-06 | PM | 100.03 
105 | 2011-10-06 | PM | 250.74 
106 | 2011-10-06 | PM | 180.44 
107 | 2011-10-06 | PM | 150.10 

這是我的查詢到目前爲止(顯然有什麼問題)

SELECT A.id AS ID, A.gift_cards_sold AS A_SOLD, B.gift_cards_sold AS B_SOLD 
FROM A 
LEFT JOIN B 
USING (id) 
WHERE A.am_pm = 'PM' 
AND A.business_date = '2011-10-06' 
AND B.business_date = '2011-10-06' 
GROUP BY A.id 
ORDER BY A.id ASC 

下面是結果:

| id | A_SOLD | B_SOLD | 
======================== 
103 | 175.03 | 100.03 
105 | 250.74 | 250.74 
106 | 180.44 | 180.44 
107 | 150.10 | 150.10 

正如你所看到的,是用103號方差不過,我需要的結果顯示每一個ID,無論是否有匹配與否。結果集是我期望使用Inner Join的結果。

回答

1

只需從WHERE移動B.business_date = '2011-10-06'條件的ON條款。當您有LEFT聯接時,關於第二個表格列(除IS (NOT) NULL之外)的WHERE條件實際上取消LEFT JOIN,則它將作爲INNER JOIN

SELECT A.id AS ID 
    , A.gift_cards_sold AS A_SOLD 
    , B.gift_cards_sold AS B_SOLD 
FROM A 
    LEFT JOIN B 
    ON B.id = A.id 
    AND B.business_date = '2011-10-06' 
WHERE A.am_pm = 'PM' 
    AND A.business_date = '2011-10-06' 
ORDER BY A.id 
+0

感謝您的幫助。 – Brett

1

你應該使用這樣的事情:你爲什麼用

SELECT A.id AS ID, A.gift_cards_sold AS A_SOLD, B.gift_cards_sold AS B_SOLD 
FROM A 
LEFT JOIN B 
USING (id) 
WHERE A.am_pm = 'PM' 
AND A.business_date = '2011-10-06' 
AND (B.business_date = '2011-10-06' or B.business_date is null) 
GROUP BY A.id 
ORDER BY A.id ASC 
0

問題是與B.business_date WHERE條件,也應該允許空

SELECT A.id AS ID, A.gift_cards_sold AS A_SOLD, B.gift_cards_sold AS B_SOLD 
FROM A LEFT JOIN B ON A.id = B.id 
WHERE A.am_pm = 'PM' 
AND A.business_date = '2011-10-06' 
AND (B.business_date = '2011-10-06' OR B.business_date is null) 
ORDER BY A.id ASC 
1

我不知道一個「group by」子句 - 這裏不需要,而在大多數其他數據庫中,這會是一個語法錯誤。

我假設你只需要匹配id上的行。

這應該工作:

select A.id AS ID, A.gift_cards_sold AS A_SOLD, B.gift_cards_sold AS B_SOLD 
from A left join b on b.id = a.id 
where A.business_date = '2011-10-06' 
    and A.am_pm = 'PM' 
order by a.id 
+0

「Group By」不需要。我從習慣中輸入它,謝謝。 – Brett

+0

人們建議左連接B,然後添加'或B.xxx爲空'顯然不明白左連接是什麼。 – GreyBeardedGeek