MySQL中获取天、周、月等数据
日
1.今天
select * from 表名 where to_days(时间字段名) = to_days(now());
2.昨天
select * from 表名 where to_days(now( ) ) - to_days(时间字段名) <= 1
3.近7天
select * from 表名 where date_sub(curdate(), interval 7 day) <= date(时间字段名)
4.获取本月最后一天
select last_day(curdate());
5.获取本月第一天
select date_add(curdate(),interval -day(curdate())+1 day);
6.获取下个月的第一天
select date_add(curdate()-day(curdate())+1,interval 1 month);
7.获取当前月的天数
select datediff(date_add(curdate()-day(curdate())+1,interval 1 month ),date_add(curdate(),interval -day(curdate())+1 day));
周
1.查询当前周的数据
查询本周所有的数据(本周第一天是周日)
select * from 表名 where yearweek(date_format(时间字段,'%Y-%m-%d')) = yearweek(now());
查询本周所有的数据(本周第一天是周一)
select * from 表名 where yearweek(date_format(时间字段,'%Y-%m-%d'),1) = yearweek(now(),1);
----------------------------------------------------------------------
2.查询上周的数据
select * from 表名 where yearweek(date_format(时间字段名,'%Y-%m-%d')) = yearweek(now())-1;
月
1.本月
-- (方法一)
select * from 表名 where date_format(时间字段名,'%Y%m') = date_format(curdate(),'%Y%m' )
select * from 表名 where date_format(时间字段名,'%Y-%m') = date_format(now(),'%Y-%m')
--(方法二)
select * from 表名 where weekofyear(from_unixtime(时间字段名,'%y-%m-%d')) = weekofyear(now())
--(方法三)
select * from 表名 where month(from_unixtime(时间字段名,'%y-%m-%d')) = month(now())
select * from 表名 where year(from_unixtime(时间字段名,'%y-%m-%d')) = year(now()) and month(from_unixtime(时间字段名,'%y-%m-%d')) = month(now())
----------------------------------------------------------------------
2.查询上个月的数据
-- (方法一)
select * from 表名 where period_diff(date_format(now(),'%Y%m' ),date_format(时间字段名, '%Y%m')) =1-
--(方法二)
select * from 表名 where date_format(秒数列,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')
----------------------------------------------------------------------
3.距离现在6个月之前的数据
select * from 表名 where 时间字段名 between date_sub(now(),interval 6 month) and now();
季度
1.查询本季度数据
select * from 表名 where quarter(时间字段名)=quarter(now());
2.查询上季度数据
select * from 表名 where quarter(时间字段名)=quarter(date_sub(now(),interval 1 quarter));
年
1.查询本年数据
select * from 表名 where year(时间字段名)=year(now());
2.查询上年数据
select * from 表名 where year(时间字段名)=year(date_sub(now(),interval 1 year));