mysql 查询当天、本周,本月,上一个月等时间段的数据

今天
select * from table where to_days(time_column) = to_days(now());


昨天
SELECT * FROM table WHERE TO_DAYS( NOW( ) ) - TO_DAYS( time_column) <= 1;


近7天
SELECT * FROM table where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(time_column);


近30天
SELECT * FROM table where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(time_column);


本月
SELECT * FROM table WHERE from_unixtime( time_column, '%Y%m' ) = from_unixtime( CURDATE( ) , '%Y%m' );


上一月
SELECT * FROM table WHERE PERIOD_DIFF( from_unixtime( now( ) , '%Y%m' ) , from_unixtime( time_column, '%Y%m' ) ) =1;


查询本季度数据
select * from table where QUARTER(create_date)=QUARTER(now());


查询上季度数据
select * from table where QUARTER(create_date)=QUARTER(DATE_SUB(now(),interval 1 QUARTER));


查询本年数据
select * from table where YEAR(create_date)=YEAR(NOW());


查询上年数据
select * from table where year(create_date)=year(date_sub(now(),interval 1 year));


查询当前这周的数据
SELECT name,time_column FROM table WHERE YEARWEEK(from_unixtime(time_column,'%Y-%m-%d')) = YEARWEEK(now());


查询上周的数据
SELECT name,time_column FROM table WHERE YEARWEEK(from_unixtime(time_column,'%Y-%m-%d')) = YEARWEEK(now())-1;


查询上个月的数据
select name,time_column from table where from_unixtime(time_column,'%Y-%m')=from_unixtime(DATE_SUB(curdate(), INTERVAL 1 MONTH),'%Y-%m')


select * from table where from_unixtime(time_column,'%Y%m') = from_unixtime(CURDATE(),'%Y%m') ; 


select * from table where WEEKOFYEAR(FROM_UNIXTIME(time_column,'%y-%m-%d')) = WEEKOFYEAR(now()) 


select * from table where MONTH(FROM_UNIXTIME(time_column,'%y-%m-%d')) = MONTH(now()) 


select * from table where YEAR(FROM_UNIXTIME(time_column,'%y-%m-%d')) = YEAR(now()) and MONTH(FROM_UNIXTIME(time_column,'%y-%m-%d')) = MONTH(now()) 


select * from table where time_column between  上月最后一天  and 下月第一天 


查询当前月份的数据 
select name,time_column from table where from_unixtime(time_column,'%Y-%m')=from_unixtime(now(),'%Y-%m');


查询距离当前现在6个月的数据
select name,time_column from table where time_column between date_sub(now(),interval 6 month) and now();

猜你喜欢

转载自blog.csdn.net/sinat_18755913/article/details/79817855