MySQL查询零值

时间:2012-06-05 08:57:04

标签: mysql count

我有这两个表(文章和销售):

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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