2012-06-05 91 views
0

我有這兩個表(文章和銷售):MySQL查詢與零值

id | name  | 
====+============ 
1 | milk | 
2 | apple | 
3 | bread | 
... | ... | 


id | idArticle | date  | 
====+==============+============= 
1 |  2  | 2011-01-01 | 
2 |  2  | 2011-01-01 | 
3 |  3  | 2011-01-01 | 
4 |  1  | 2011-01-02 | 
... |  ...  | ...  | 

我需要獲得2011/01/01銷售:文章和計數

2011-01-01 Milk 0 
2011-01-01 Apple 2 
2011-01-01 Bread 1 
... 

但我不知道如何顯示「牛奶:0」,因爲那天沒有賣牛奶。

該查詢不起作用:

SELECT s.date, a.name, COUNT(*) 
FROM article a 
LEFT JOIN sale s ON a.id = s.idArticle 
WHERE s.date = "2011-01-01" 
GROUP BY s.date, a.name 
+0

閱讀。 http://dev.mysql.com/doc/refman/5.0/en/join.html左連接是你的錯誤在這裏。嘗試內部加入 –

+0

@Bondye:但他希望**這樣,看看所需的輸出(牛奶)... –

+0

@pOcHa'但我不知道如何顯示「牛奶:0」,因爲它didn那天不賣牛奶。「你真的讀過這個問題嗎? –

回答

2
SELECT "2011-01-01" AS date, a.name, IFNULL(s.total, 0) 
FROM article a 
LEFT JOIN (
    SELECT idArticle, COUNT(*) AS total 
    FROM sale 
    WHERE date = "2011-01-01" 
    GROUP BY idArticle 
) AS s ON a.id = s.idArticle 
+0

感謝pOcHa,它工作了一天 – Stokres

+0

只是將「2011-01-01」更改爲@date參數,並且它將適用於任何一天 - 如果您希望它在日期範圍內,則更改'WHERE date =「 2011-01-01「'to'WHERE date BETWEEN @dateMin AND @ dateMax',但從select中刪除日期列... –

0
SELECT a.name, COUNT(s.id) 
FROM article a 
LEFT JOIN sale s ON a.id = s.idArticle AND s.date = '2011-01-01' 
GROUP BY a.name 
+0

什麼是你計算沒有'GROUP BY a.name' –

+0

@pOcHa Thx,錯過了,固定。 – xdazz