2013-05-19 84 views
8

我有一组月度职位。现在我需要一个数组,其中包含每个月发布的帖子的总记录。我在MySql查询下面试过,它的工作正常,但我在没有记录的月份期待0(零)。这里它不返回0.如果没有找到记录,MySql count()返回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 

得到了结果:

+----------+ 
| totalRec | 
+----------+ 
|  7 | 
|  9 | 
+----------+ 

预期结果(凡有一月没有职位):

+----------+ 
| totalRec | 
+----------+ 
|  0 | 
|  7 | 
|  9 | 
+----------+ 

样本数据:

+----+---------------------+ 
| 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 | 
+----+---------------------+ 
+1

你可以给样本记录,我们可以一起玩? –

+0

你GROUP BY看上去不正确 –

+0

@JW웃我已经编辑我的问题与样本数据.. – sravis

回答

15

有用于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 

输出

╔══════════╗ 
║ TOTALREC ║ 
╠══════════╣ 
║  0 ║ 
║  7 ║ 
║  9 ║ 
╚══════════╝ 
+0

不错的一个。我也正在做一个sql小提琴。但你击败了我 - 像往常一样:) +1 – luksch

+0

哇,非常感谢。我试着从过去的1小时里得到这个结果,最后你节省了我的时间。非常感谢你。 – sravis

+0

@JW我在你的JSfiddle例子的选择列表中添加了April Month,所以结果应该是[0,7,9,0],但是它显示[0,7,9]。你能看到它吗? http://www.sqlfiddle.com/#!2/e0a6e/15 – sravis

3

您是否尝试过IFNULL()正确的方法?也许尝试IFNULL(Count(id), 0)SELECT子句加入。

3

COALESCE是你可以使用的东西,如果你有日期的表和左加入了反对。它从左到右返回第一个非null值。 你的小组在我看来有点坚果,我已经调整了它。

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 

哪里日期表..

DATE 
2013-01-01 
2013-01-02 
2013-01-03 
etc.... 

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

+0

我想你的查询,我仍然得到同样的结果 – sravis

+0

对不起,我错过了日期表创建位,这就是重要的 –

1

如果结果集在这段时间内没有任何职位,你不会得到任何结果来算,因此为什么不显示。

您将需要要么加入到具有所有的年月另一个表或数据编程填写返回结果时。我想不出另一种方式来做到这一点,但也许这是可能的。

另外,正如其他人所说,用逗号分隔组。

0

我想你只需要这样的查询

SELECT COALESCE(COUNT(id),0) AS totid FROM table 

VB例子

Set count=Con.Execute("SELECT COALESCE(COUNT(id),0) AS totid FROM table") 

然后写

<%=count("totid")%> 
相关问题