如果使用MySQL在数据库中不存在数据,如何获取计数0

时间:2019-06-17 06:33:31

标签: javascript mysql sql mysql-workbench

我正在显示每月在我的应用程序中注册的用户。为此,我使用了以下查询,效果很好。但是通过此查询,如果6月没有用户注册,则6月没有数据。我希望将6月和其他所有信息都设置为0。有人可以帮我吗?

SELECT Month(createdon), count(*) as users,COUNT(if(roleid=1,1,NULL)) as instructor, COUNT(if(roleid=2,1,NULL)) as student FROM user_profile where Year(createdon) = Year(Now()) group by MONTH(createdon);

我得到的输出为:

Month(created on) | users | instructor | student | 3 | 4 | 3 | 1 | 4 | 7 | 5 | 2 |

第3个月和第4个月分别对应于3月和4月。

但是实际输出是:

Month(created on) | users | instructor | student | 1 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 3 | 4 | 3 | 1 | 4 | 7 | 5 | 2 | 5 | 0 | 0 | 0 | 6 | 0 | 0 | 0 |

5 个答案:

答案 0 :(得分:1)

我有同样的经历 因此,只需使用

SELECT IF( EXISTS (SELECT * FROM user_profile WHERE MONTH(createdon)= 'yourmonth')
  ,SELECT 
     Month(createdon),
     COUNT(*) AS users,
     COUNT(if(roleid=1,1,NULL)) AS instructor, 
     COUNT(if(roleid=2,1,NULL)) AS student 
  FROM user_profile 
  WHERE Year(createdon) = Year(Now()) 
  Group BY MONTH(createdon)
,0)

答案 1 :(得分:1)

您可以尝试以下方法:

SELECT MONTH(createdon) AS month, COUNT(*) AS users, COUNT(IF(roleid=1,1,NULL)) AS instructor, COUNT(IF(roleid=2,1,NULL)) AS student
FROM user_profile
WHERE (YEAR(createdon) = YEAR(NOW()))
GROUP BY MONTH(createdon)
UNION
SELECT M.month, 0, 0, 0
FROM (SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS M
WHERE (M.month <= MONTH(NOW()))
  AND (NOT EXISTS (SELECT * FROM user_profile WHERE (MONTH(createdon) = M.month)));

答案 2 :(得分:0)

您可以收集排序后的SQL结果并迭代自定义范围,然后插入给定数据或空结果集。

function getRange(from, to, result) {
    var i, j = 0;
    for (i = from; i <= to; i++) {
        if (result[j] && i === result[j][0]) {
            console.log(...result[j++]);       // slq result
        } else {
            console.log(i, 'empty row');       // row with zeroes
        }
    }
}

getRange(1, 6, [[3, 2, 5], [4, 3, 2]]);

答案 3 :(得分:0)

您没有看到row with 0 value,因为表中没有给定月份的数据,而groupby将显示存在的月份的数据。

您可以生成给定年份的月份列表-

select  TO_CHAR((current_date - interval '1 month' * a),'MM') AS mm FROM generate_series(1,12,1) AS s(a)

它将产生类似

的值
01
02
03
.
.

然后,您可以使用该表编写子查询并创建left join with your user_profile表,您将获得指定的数据。

有关更多信息,请阅读此link

答案 4 :(得分:0)

您需要从月份列表开始。这可以通过派生表来完成:

SELECT m.mon, COUNT(up.createdon) as users,
       SUM(up.roleid = 1) as instructor,  
       SUM(up.roleid = 2) as student
FROM (SELECT 1 as mon UNION ALL
      SELECT 2 as mon UNION ALL
      SELECT 3 as mon UNION ALL
      SELECT 4 as mon UNION ALL
      SELECT 5 as mon UNION ALL
      SELECT 6 as mon 
     ) m LEFT JOIN
     user_profile up
     ON m.mon = MONTH(up.createdon) AND
        YEAR(createdon) = YEAR(Now()) 
GROUP BY m.mon;

如果您有日历表或数字表,则可以使用它代替派生表。