標籤:
問題:
Mysql表中一列create_time,類型datetime(YYYY-MM-DD HH:MM:SS),想擷取上個月今天到昨天的資料。
select * from 表名 where date_format(create_time,‘%Y-%m-%d‘) between date_sub(curdate(),interval 1 MONTH) and date_sub(curdate(),interval 1 day)
仔細研究了下,Mysql有很多時間類型。
/*今天*/
select * from 表名 where to_days(時間欄位) = to_days(now());
/*昨天*/
select * from 表名 where to_days(now())-to_days(時間欄位) = 1;
/*近7天*/
select * from 表名 where date_sub(curdate(), interval 7 day) <= date(時間欄位);
/*查詢距離當前現在6個月的資料*/
select * from 表名 where 時間欄位 between date_sub(now(),interval 6 month) and now();
/*查詢當前這周的資料*/
select * from 表名 where yearweek(date_format(時間欄位,‘%Y-%m-%d‘)) = yearweek(now());
/*查詢上周的資料*/
select * from 表名 where yearweek(date_format(時間欄位,‘%Y-%m-%d‘)) = yearweek(now())-1;
/*查詢當前月份的資料*/
select * from 表名 where date_format(時間欄位,‘%Y-%m‘)=date_format(now(),‘%Y-%m‘);
/*查詢上個月的資料*/
select * from 表名 where date_format(時間欄位,‘%Y-%m‘)=date_format(date_sub(curdate(), interval 1 month),‘%Y-%m‘);
Mysql 求時間 between 昨天 and 上個月的今天 等時間函數