即使count = 0 mysql也要选择

时间:2015-01-11 15:55:05

标签: mysql sql date count

所以我有3张桌子:

 accident, involve and car. 
 Car (registration_nr, model,year)
 involve (licence_nr,registration_nr (FK of car), raport_nr (FK of accident))
 accident(raport_nr, date)

从2014年1月1日起,我必须计算每种车型的事故数量,但必须选择0号车(从01年1月1日起未发生事故)这是很难的部分。我,直到现在我只能选择那些发生意外的人。

Select c.model,count(m.registration_nr)
from car as c
join involve as i
on i.registration_nr=c.registration_nr
join  accident as a
on i.raport_nr=a.raporti_nr 
where a._date between '2014-01-01' and curdate() 
group by c.model;

3 个答案:

答案 0 :(得分:0)

你清楚地说明你只想要有意外的行:

where a._date between '2014-01-01' and curdate() 

只需添加OR子句即可将记录设为a._date IS NULL

答案 1 :(得分:0)

您可以使用条件聚合:

Select c.model, sum(a._date between '2014-01-01' and curdate() )
from car c left join
     involve i
     on i.registration_nr = c.registration_nr left join
     accident a
     on i.raport_nr = a.raporti_nr 
group by c.model;

我还添加了left join - 以防某些型号完全没有发生意外。

答案 2 :(得分:0)

我遇到了同样的问题,我花了很长时间才搞清楚。 事实证明,如果集合全部为NULL,则聚合函数COUNT将返回0。所以这是你如何提出查询:

SELECT model, COUNT(registration_nr)
FROM car LEFT JOIN (involve NATURAL JOIN accident) USING (registration_nr)
WHERE date > '01-01-2014' OR date IS NULL
GROUP BY model

就我而言,输出类似于:

Model     Count
Mazda     1
Honda     0