小编典典

如果group by不返回任何值,则显示零

sql

我试图获得过去7天注册的用户数量以显示在图表上,如果mysql返回0而不是没有行,那将是很好的。目前,它只返回每天都有一行值的行

SELECT   date(created_at), 
         count(id) 
FROM     user_accts 
WHERE    date(created_at) < NOW() 
AND      date(created_at) > DATE_SUB(NOW(), INTERVAL 7 DAY) 
GROUP BY date(created_at);

阅读 313

收藏
2021-04-14

共1个答案

小编典典

尝试:

SELECT DATE_SUB(CURDATE(), INTERVAL i DAY) date_created_at, 
       count(id) 
FROM (SELECT 1 i UNION ALL 
      SELECT 2 UNION ALL 
      SELECT 3 UNION ALL 
      SELECT 4 UNION ALL 
      SELECT 5 UNION ALL 
      SELECT 6 UNION ALL 
      SELECT 7) i
LEFT JOIN user_accts ON  date(created_at) = DATE_SUB(CURDATE(), INTERVAL i DAY)
                   /*AND owner_id = '131'*/
GROUP BY DATE_SUB(CURDATE(), INTERVAL i DAY)
2021-04-14