Mysql Count and group by date在没有值时应返回0
我想报告我们每天的采访次数 所以我有一张采访表 比如 受访者ID、职员、日期、评论 以及包含2005年至2020年所有日期的日期参考表。有一个名为ref的日期字段 我的问题是:Mysql Count and group by date在没有值时应返回0,mysql,count,group-by,Mysql,Count,Group By,我想报告我们每天的采访次数 所以我有一张采访表 比如 受访者ID、职员、日期、评论 以及包含2005年至2020年所有日期的日期参考表。有一个名为ref的日期字段 我的问题是: SELECT count(*) as cnt FROM `interviews` right JOIN `dateRef` ON `date` = ref where type = 2 and date > date_sub(now(),interval 7 day) group by date_format(
SELECT count(*) as cnt FROM `interviews`
right JOIN `dateRef` ON `date` = ref where type = 2
and date > date_sub(now(),interval 7 day) group by date_format(ref,'%Y-%m-%d')
可以显示我们做过的采访,但不可以显示我们没有做任何采访的时候
例如,这将返回:
1
2
4
但它应该会回来
0
1
0
2
0
4
0
编辑:
显然,问题来自where子句,因为如果我删除它,查询工作正常…尝试替换
right join
反而
left join
另一个变化是
where type = 2
到
那么最后的查询
SELECT count(*) as cnt FROM `interviews`
right JOIN `dateRef` ON `date` = ref where (type = 2 OR type is null)
and date > date_sub(now(),interval 7 day) group by date_format(ref,'%Y-%m-%d')
如果我理解正确,
type
是一列采访。由于您使用的是右联接,因此联接表包含不带面谈的日期行,但这些行在列type
(以及面谈
的任何其他列)中具有NULL
,因为面谈
表中没有这些日期的条目。它们被WHERE
子句过滤掉,该子句要求type=2
,这就是COUNT
看不到它们的原因
您可以尝试类似于的方法,其中(type=2或type为NULL)
,至少在采访时是这样。type
永远不会为NULL
SELECT count(*) as cnt FROM `interviews`
right JOIN `dateRef` ON `date` = ref where (type = 2 OR type is null)
and date > date_sub(now(),interval 7 day) group by date_format(ref,'%Y-%m-%d')