如果没有找到记录,MySql count()返回0

sra*_*vis 8 mysql sql

我每月都有一套帖子.现在我需要一个数组,其中包含每个月发布的帖子的总记录.我在MySql下面尝试查询,它的工作正常,但是在没有记录的几个月里,我期待0(零).这里没有返回0.

我读到COUNT()不会返回'0',那我怎么做到这一点?

我尝试了IFNULL()和COALESCE(),但仍然得到了相同的结果.请帮助解决此问题.谢谢......

SELECT
count(id) as totalRec
FROM ('post')
WHERE year(date) =  '2013'
AND monthname(date) IN ('January', 'February', 'March') 
GROUP BY year(date)-month(date)
ORDER BY 'date' ASC
Run Code Online (Sandbox Code Playgroud)

得到的结果:

+----------+
| totalRec |
+----------+
|        7 |
|        9 |
+----------+
Run Code Online (Sandbox Code Playgroud)

预期结果(1月份没有帖子):

+----------+
| totalRec |
+----------+
|        0 |
|        7 |
|        9 |
+----------+
Run Code Online (Sandbox Code Playgroud)

样本数据:

+----+---------------------+
| id | date                |
+----+---------------------+
| 24 | 2012-12-16 16:29:56 |
|  1 | 2013-02-25 14:57:09 |
|  2 | 2013-02-25 14:59:37 |
|  4 | 2013-02-25 15:12:44 |
|  5 | 2013-02-25 15:14:18 |
|  7 | 2013-02-26 11:31:31 |
|  8 | 2013-02-26 11:31:59 |
| 10 | 2013-02-26 11:34:47 |
| 14 | 2013-03-04 04:39:02 |
| 15 | 2013-03-04 05:44:44 |
| 16 | 2013-03-04 05:48:29 |
| 19 | 2013-03-07 15:22:34 |
| 20 | 2013-03-15 12:24:43 |
| 21 | 2013-03-16 16:27:43 |
| 22 | 2013-03-16 16:29:28 |
| 23 | 2013-03-16 16:29:56 |
| 11 | 2013-03-17 11:35:12 |
+----+---------------------+
Run Code Online (Sandbox Code Playgroud)

Joh*_*Woo 16

这个月没有记录,January这就是为什么你没有得到任何结果.一个有效的解决方案是加入一个子查询,其中包含您希望在列表中显示的月份列表.

SELECT count(b.id) as totalRec
FROM   (
            SELECT 'January' mnth
            UNION ALL
            SELECT 'February' mnth
            UNION ALL
            SELECT 'March' mnth
        ) a
        LEFT JOIN post b
            ON a.mnth = DATE_FORMAT(b.date, '%M') AND
               year(b.date) =  '2013' AND 
               DATE_FORMAT(b.date, '%M') IN ('January', 'February', 'March') 
GROUP  BY year(b.date)-month(b.date) 
ORDER  BY b.date ASC
Run Code Online (Sandbox Code Playgroud)

OUTPUT

????????????
? TOTALREC ?
????????????
?        0 ?
?        7 ?
?        9 ?
????????????
Run Code Online (Sandbox Code Playgroud)


kir*_*off 5

你尝试IFNULL()正确的方法了吗?也许尝试加入IFNULL(Count(id), 0)一个SELECT子句。


Pau*_*ley 5

COALESCE如果您有一个日期表并左连接它,那么您可以使用它。它从左到右返回第一个非空值。你的小组现在看起来有点疯狂,我已经调整过了。

SELECT
COALESCE(count(id),0) as totalRec
FROM ('post')
LEFT JOIN dates
ON dates.date = post.date
WHERE year(date) =  '2013'
AND monthname(date) IN ('January', 'February', 'March') 
GROUP BY month(date), year(date)
ORDER BY 'date' ASC
Run Code Online (Sandbox Code Playgroud)

日期表在哪里..

DATE
2013-01-01 
2013-01-02
2013-01-03
etc....
Run Code Online (Sandbox Code Playgroud)

见这里:http : //easywebapps.blogspot.co.uk/2011/07/mysql-how-to-create-calendar-table.html