【问题标题】:MySql count() to return 0 if no records found如果没有找到记录,MySql count() 返回 0
【发布时间】:2013-05-19 15:43:37
【问题描述】:

我每个月都有一组帖子。现在我需要一个数组,其中包含每个月发布的帖子的总记录。我在 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

得到结果:

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

【问题讨论】:

  • 你能提供我们可以玩的样本记录吗?
  • 你的分组看起来不正确
  • @JW웃 我已经用示例数据编辑了我的问题..

标签: mysql sql


【解决方案1】:

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 ║
╚══════════╝

【讨论】:

  • @JW 我在您的 JSfiddle 示例中的选择列表中添加了 April Month,因此结果应该是 [0,7,9,0] 但它显示的是 [0,7,9]。你能看一次吗? sqlfiddle.com/#!2/e0a6e/15
  • 这真的帮助我完成了一些类似的事情:--get count of pots used and next1 use plants go select a.pot, count(b.pot_info) as number from (select pot_info as pot from pots union select next1 from pots)a left join 植物 b on a.pot=b.pot_info group by a.pot order by a.pot
【解决方案2】:

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

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

【讨论】:

  • 对不起,我错过了日期表创建位,这很重要
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    如果结果集在该时间段内没有帖子,您将不会得到任何结果来计算,因此它不显示。

    您需要加入另一个包含全年月份的表,或者在返回结果时以编程方式填写数据。我想不出另一种方法来做到这一点,但也许这是可能的。

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

    【讨论】:

      【解决方案5】:

      试试这样::

      SELECT
        count(id) as totalRec
        IF(id NULL, 0, id) As IdList
      FROM ('post')
       WHERE year(date) =  '2013'
        AND monthname(date) IN ('January', 'February', 'March') 
        GROUP BY year(date)-month(date)
      ORDER BY 'date' ASC
      

      在 MySQL 中返回 0 而不是 null
      使用

      SELECT id, IF(age IS NULL, 0, age) FROM tblUser

      使用 count() 连接 2 个表

      表格

      tblA

      tblA_Id    Name     
      -----------------
          1       HSP     
          2       MANI     
          3       MEET     
          4       user    
          5       jaani   
      

      tblB

      tblB_Id    SongName  tblA_Id
       -----------------------------
          1        song1     3
          2        song2     3
          3        song3     1
          4        song4     1
          5        song4     5
      

      查询

      SELECT 
          tblA.tblA_Id,
          tblA.Name,
          tblC.SongCount,
          IF(tblC.SongCount IS NULL, 0, tblC.SongCount) As noOfSong
        FROM  tblA
          LEFT JOIN
          (   
              SELECT 
                  ArtistId,count(*) AS SongCount 
              FROM 
                  tblB  
              GROUP BY 
                  ArtistId
          ) AS tblC
          ON 
              tblA.tblA_Id = NoOfSong.ArtistId
      

      结果是

       tblA_Id    Name     SongCount   noOfSong
       -------------------------------------------
          5       jaani    1           1
          4       user     NULL        0
          3       MEET     2           2
          2       MANI     NULL        0
          1       HSP      2           2 
      

      【讨论】:

        【解决方案6】:

        我认为你只需要这样的查询

        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")%>
        

        【讨论】:

          【解决方案7】:

          您可以尝试简单地使用您的 sql。 我的旧sql是这样的

          select c.*, dynamic_count from channel c 
              left join (select channel_id, count(*) as dynamic_count from dynamic group by channel_id) d
                       on c.id = d.channel_id;
          

          如果动态不匹配,我会得到 null。但是如果我像这样更改我的 sql:

          select c.*, count(d.id) as dynamic_count from channel c
              left join dynamic d on c.id = d.channel_id
              group by c.id;
          

          如果没有动态匹配,我得到 0; 希望对您有所帮助!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-07-24
            • 1970-01-01
            • 2020-10-05
            • 1970-01-01
            相关资源
            最近更新 更多