MySQL查询今天,最近7天,最近30天,本月,上个月的数据
其中一个故事story的表,存储故事添加的时间是create_time,查询今天添加的文章总数并且按时间从大到小排序,查询如下:
如果create_time为2015-01-20 14:02:22样式:
select * from story where DATE_FORMAT(create_time,"%Y-%m-%d")= DATE_FORMAT(now(),"%Y-%m-%d") order by create_time desc;
如果create_time为int(5)类型:
select * from story where date_format(FROM_UNIXTIME(create_time),"%Y-%m-%d") = DATE_FORMAT(now(),"%Y-%m-%d");
假设以上表的create_time字段的存储类型是DATETIME类型或者TIMESTAMP类型,则查询语句也可按如下写法:
查询今天的记录:
select * from story where to_days(create_time) = to_days(now());
查询昨天的记录:
select * from story where to_days(now()) - to_days(create_time) = 1;
查询近7天的信息记录:
select * from story where DATE_SUB(CURDATE(),INTERVAL 7 DAY) <= DATE(create_time);
查询近30天的信息记录:
select * from story where DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= DATE(create_time);
查询本月的信息记录:
select * from story where DATE_FORMAT(create_time,"%Y-%m") = DATE_FORMAT(CURDATE(),"%Y-%m");
查询上月的信息记录:
select * from story where PERIOD_DIFF(DATE_FORMAT(NOW(),"%Y-%M"),DATE_FORMAT(create_time,"%Y-%m")) = 1;
- 上一篇: MySQL查询一小时之内的数据
- 下一篇: MySQL内置函数获取几天前的日期