mysql查询今天,昨天,近7天,近30天,本月,上一月数据,mysql一月
最近项目中用到了查询当月数据记录的功能,最初的想法是在逻辑业务里构造好时间段进行查询,当写sql语句时感觉挺麻烦。所以就到网上搜索了一下,看看是不是能有简单的方法。果然,网络资源很强大。下面结合我的项目表来把mysql查询今天,昨天,近7天,近30天,本月,上一月数据的sql语句记录一下。
有一张ad_proTrack_t 表,追踪产品时间字段为crt_time
查询今天的信息记录:
select * from ad_proTrack_t where to_days(`crt_time`) = to_days(now());查询昨天的信息记录:
select * from ad_proTrack_t where to_days(now()) – to_days(`crt_time`) <= 1;查询近7天的信息记录:
select * from ad_proTrack_t where date_sub(curdate(), INTERVAL 7 DAY) <= date(`crt_time`);查询近30天的信息记录:
select * from ad_proTrack_t where date_sub(curdate(), INTERVAL 30 DAY) <= date(`crt_time`);查询本月的信息记录:
select * from ad_proTrack_t where date_format(`crt_time`, ‘%Y%m') = date_format(curdate() , ‘%Y%m');查询上一月的信息记录:
select * from ad_proTrack_t where period_diff(date_format(now() , ‘%Y%m') , date_format(`crt_time`, ‘%Y%m')) =1;
select * from tb_user where datediff('d',log_time,now)=0
select * from tb_user where datediff('d',log_time,now)=1
select * from tb_user where datediff('d'log_time,now)=7
select * from tb_user where datediff('d'log_time,now)=30
select * from wap_content where week(created_at) = week(now)
如果你要严格要求是某一年的,那可以这样
查询一天:
select * from table where to_days(column_time) = to_days(now());
select * from table where date(column_time) = curdate();
查询一周:
select * from table where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(column_time);
查询一个月:
select * from table where DATE_SUB(CURDATE(), INTERVAL INTERVAL 1 MONTH) <= date(column_time);