mysql - 如果没有记录,我怎么能算作 0?

标签 mysql date

我有这样的问题

select `temp`, IfNULL(count(id),0) t 
from survey 
where `temp`<>'NULL' and `temp`<> '' and date(submitdate)='date' 
group by `temp

有 o/p

temp        t
A1          1

但如果没有记录,则在所选日期会发生以下情况:我没有得到任何结果。答案像 A1,A2,A3

我需要这样的o/p

temp   t
A1     1
A2     0
A3     0

最佳答案

您将不得不使用一些自JOIN 技巧来获取每个答案的记录:

SELECT s.`temp`, count(survey.id) t
-- This will ensure that you will get all relevant answers A1, A2, A3
FROM (
  SELECT DISTINCT `temp`
  FROM survey
  WHERE `temp` <> 'NULL' and `temp` <> ''
--             ^^^^^^^^^ Might want to replace this by `temp` IS NOT NULL?
) s
-- Only then, you will actually get the actual records per answer and date
LEFT OUTER JOIN survey
  ON s.`temp` = survey.`temp`
  AND date(survey.submitdate) = 'date'
GROUP BY s.`temp`

请确保您在 survey.temp 上有一个索引。

关于mysql - 如果没有记录,我怎么能算作 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13288777/

相关文章:

javascript - FullCalendar GMT +0200 日期

mysql - 将两个选项卡的结果组合成一行

mysql - 如何连接到远程服务器上的数据库

php - 在 PHP 中内爆来自 Json 的数组

php - 使用 PHP 检查变量是否为有效日期

python - Pandas 中一天的第一个和最后一个值 (Python)

mysql - 如何通过mysql查询从考勤表中获取考勤报告?

mysql - 将一列从一个表复制到另一个

ruby - 查找集合中的最短日期 (Ruby)

python/pandas 查找两个日期之间的年数