Mysql计数结果为零值

时间:2011-11-21 12:57:43

标签: mysql count row zero

在mysql中,我得到了表“得分”如下

Id  Date                Name        score
1   2011-08-24 00:00:00 sharique    10
2   2011-08-24 00:00:00 joe     11
3   2011-08-24 00:00:00 vijay       5
4   2011-08-25 00:00:00 sharique    0
5   2011-08-25 00:00:00 joe    11

现在我正在运行查询

SELECT date,count(id) as count FROM scores where `name` = 'vijay' group by `date`;

我的结果为

date                 count
2011-08-24 00:00:00,  1

而不是

date                 count
2011-08-24 00:00:00,  1
2011-08-25 00:00:00,  0

我怎样才能显示零计数结果?

2 个答案:

答案 0 :(得分:9)

这是一个简单的方法:

SELECT s2.date, count(s1.id) as count
FROM (select distinct `date` from scores) s2 
  left join scores s1
    on  s1.`date` = s2.`date`
    and s1.`name` = 'vijay'
group by 1

这保证了表格中每个不同日期的每个人的日期

答案 1 :(得分:0)

您正在计算的预期结果计算与您的where条件匹配的行数。

SELECT date,count(id) as count FROM scores where `name` = 'vijay' group by `date`;

它只选择一条记录,因此计数结果为1。

如果要计算所有行,请使用Where Clause来限制数据,例如: -

SELECT date,count(id) as count FROM scores group by `date`;

同样明智的是,以下查询将返回3作为计数..

SELECT date,count(id) as count FROM scores where id in (1,2,3) group by `date`;