查詢某個時間段的資料常用的方式有
//查詢2020-09-18當天
SELECT * FROM t_user WHERE created_time between '2020-09-18 00:00:00' and '2020-09-18 23:59:59'
//查詢2020-09-18當天
SELECT * FROM t_user WHERE year(created_time ) = 2020 and month(created_time )= 09 and day(created_time ) = 18
//查詢2020-09-17 00:00:00至 2020-09-19 00:00:00
SELECT * FROM t_user WHERE created_time > '2020-09-17' and created_time < '2020-09-19'
//查詢2020-09-18當天
SELECT * FROM t_user WHERE ( datediff ( created_time , '2020-09-18' ) = 0 )
mysql還另外提供的方式還有
//今天
select * from 表名 where to_days(時間欄位) = to_days(now());
//昨天,前某一天資料直接更改日期差值的結果即可,例如查詢前天,差值為2
SELECT * FROM 表名 WHERE DATEDIFF(時間欄位,NOW())=-1;
//本週
SELECT * FROM 表名 WHERE YEARWEEK(date_format(時間欄位,'%Y-%m-%d')) = YEARWEEK(now());
//上週,同理近幾周直接更改對應的週數差值即可
SELECT * FROM 表名 WHERE YEARWEEK(date_format(時間欄位,'%Y-%m-%d')) = YEARWEEK(now())-1;
//近7天
SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(時間欄位)
//近30天,同理近多少天直接更改對應的天數即可
SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(時間欄位)
//本月
SELECT * FROM 表名 WHERE DATE_FORMAT( 時間欄位, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )
//上月,同理近幾個月直接更改對應的月數差值即可
SELECT * FROM 表名 WHERE PERIOD_DIFF( date_format( now( ) , '%Y%m' ) , date_format( 時間欄位, '%Y%m' ) ) =1
//本季度
select * from 表名 where QUARTER(時間欄位)=QUARTER(now());
//上季度,同理上上季度(2),上上上季度(3),直接更改季度數值
select * from 表名 where QUARTER(時間欄位)=QUARTER(DATE_SUB(now(),interval 1 QUARTER));
//本年
select * from 表名 where YEAR(時間欄位)=YEAR(NOW());
//去年,同理前年,大前年更改年數即可,前年為2,同理大前年為3
elect * from 表名 where year(時間欄位)=year(date_sub(now(),interval 1 year));