我如何用mysql获取最近10天的记录?

时间:2012-11-18 18:28:03

标签: mysql sql

我的表结构就像

CREATE TABLE `survey` (
  `id` int(11) NOT NULL auto_increment,
  `submitdate` datetime default NULL,
 `answer` varchar(5) collate utf8_unicode_ci default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=499 ;

现在我要计算最近10天的记录。假设特定日期没有记录。它应该为零。

输出就像

date         count
19-11-2012   10
18-11-2012   30 
13-11-2012   0 
      .
      .

我使用了像

这样的查询
SELECT COUNT( * ) , DATE( submitdate ) 
FROM survey t
WHERE t.submitdate >= ( CURDATE( ) - INTERVAL 10 
DAY ) 
GROUP BY DATE( submitdate ) 
LIMIT 0 , 30

输出

count(*)    date(submitdate)
1   2012-11-13
2   2012-11-14
1   2012-11-15
3   2012-11-16
6   2012-11-17

没有为没有日期的记录给0。

2 个答案:

答案 0 :(得分:7)

这就是你需要的:

SELECT days.day, count(survey.id)
FROM
  (select curdate() as day
   union select curdate() - interval 1 day
   union select curdate() - interval 2 day
   union select curdate() - interval 3 day
   union select curdate() - interval 4 day
   union select curdate() - interval 5 day
   union select curdate() - interval 6 day
   union select curdate() - interval 7 day
   union select curdate() - interval 8 day
   union select curdate() - interval 9 day) days
  left join survey
   on days.day = survey.submitdate
group by
  days.day

(如果提交日期包含日期和时间,则应将行on days.day = survey.submitdate替换为on days.day = DATE(survey.submitdate)

答案 1 :(得分:6)

你可以尝试这样的东西来获得输出: -

 SELECT * FROM survey t WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL -10 DAY);

或者你可以试试这个: -

 SELECT * FROM survey t WHERE t.date >= ( CURDATE() - INTERVAL 10 DAY )

检查Date_Add文档