MySql 時間操作詳解
資訊分類:
建站經驗 瀏覽:
2021年10月24日
MySql 時間操作(今天,昨天,7天,30天,本月,上月)
1 、 查看當天日期
selec t current_date();
2、 查看當天時間
selec t current_time();
3、查看當天時間日期
selec t current_timestamp();
4、查詢當天記錄
selec t * from 表名 where to_days(時間字段名) = to_days(now());
5、查詢昨天記錄
selec t * FROM 表名 WHERE TO_DAYS( NOW( ) ) – TO_DAYS( 時間字段名) <= 1
6、查詢7天的記錄
selec t * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(時間字段名)
7、查詢近30天的記錄
selec t * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(時間字段名)
8、查詢本月的記錄
selec t * FROM 表名 WHERE DATE_FORMAT( 時間字段名, ‘%Y%m’ ) = DATE_FORMAT( CURDATE( ) , ‘%Y%m’ )
9、查詢上一月的記錄
selec t * FROM 表名 WHERE PERIOD_DIFF( date_format( now( ) , ‘%Y%m’ ) , date_format( 時間字段名, ‘%Y%m’ ) ) =1
10、查詢本季度數據
selec t * from 表名 where QUARTER(create_date)=QUARTER(now());
11、查詢上季度數據
selec t * from 表名 where QUARTER(create_date)=QUARTER(DATE_SUB(now(),interval 1 QUARTER));
12、查詢本年數據
selec t * from 表名 where YEAR(create_date)=YEAR(NOW());
13、查詢上年數據
selec t * from 表名 where year(create_date)=year(date_sub(now(),interval 1 year));
14、查詢當前這周的數據
selec t * FROM 表名 WHERE YEARWEEK(date_format(submittime,'%Y-%m-%d')) = YEARWEEK(now());
15、查詢上周的數據
selec t * FROM 表名 WHERE YEARWEEK(date_format(submittime,'%Y-%m-%d')) = YEARWEEK(now())-1;
16、查詢當前月份的數據
selec t * from 表名 where date_format(submittime,'%Y-%m')=date_format(now(),'%Y-%m')
17、查詢距離當前現在6個月的數據
selec t name,submittime from enterprise where submittime between date_sub(now(),interval 6 month) and now();