Mysql 日期格式化 复杂日期区间查询
前言#
最近在做项目涉及到Mysql
的复杂日期查询,日期查询其实在数据库中查询其实还是用的挺多的,比如查询开始日期到结束日期的区间信息,查询日期小于有效日期的信息,查询当天的日期,明天的日期,做比较等。
查询使用场景案例#
- 时间区间查询
查询,2021年06月01号到2021年08月25号的数据
SELECT * FROM `dateTest` where DATE_FORMAT(date,'%Y%m%d') BETWEEN '20210601' and '20210825'
包括开始时间,不包括结束时间
但是DATE_FORMAT(date,'%Y%m')这种写法,无法使用索引,数据量大了以后查询超级慢
查询日期今天时间比较数据
select * from t_user t where t.CREATE_TIME>=curdate()
通过DATE
把时间日期转换为时间格式
select * from t_user t where DATE (t.CREATE_TIME)>=DATE (now())
常用的周期时间查询
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
-- 今天 select fullName,addedTime from t_user where to_days(addedTime) <= to_days(now()); -- 昨天 select fullName,addedTime from t_user where to_days(NOW()) - TO_DAYS(addedTime) <= 1; -- 近7天 select fullName,addedTime from t_user where date_sub(CURDATE(),INTERVAL 7 DAY) <= DATE(addedTime); -- 近30天 SELECT fullName,addedTime FROM t_user where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(addedTime); -- 本月 SELECT fullName,addedTime FROM t_user WHERE DATE_FORMAT( addedTime, '%Y%m' ) = DATE_FORMAT( CURDATE() , '%Y%m' ); -- 上一月 SELECT fullName,addedTime FROM t_user WHERE PERIOD_DIFF( date_format( now( ) , '%Y%m' ) , date_format( addedTime, '%Y%m' ) ) =1; -- 查询本季度数据 select fullName,addedTime FROM t_user where QUARTER(addedTime)=QUARTER(now()); -- 查询上季度数据 select fullName,addedTime FROM t_user where QUARTER(addedTime)=QUARTER(DATE_SUB(now(),interval 1 QUARTER)); -- 查询本年数据 select fullName,addedTime FROM t_user where YEAR(addedTime)=YEAR(NOW()); -- 查询上年数据 select fullName,addedTime FROM t_user where year(addedTime)=year(date_sub(now(),interval 1 year)); -- 查询距离当前现在6个月的数据 select fullName,addedTime FROM t_user where addedTime between date_sub(now(),interval 6 month) and now(); -- 查询当前这周的数据 SELECT fullName,addedTime FROM t_user WHERE YEARWEEK(date_format(addedTime,'%Y-%m-%d')) = YEARWEEK(now()); -- 查询上周的数据 SELECT fullName,addedTime FROM t_user WHERE YEARWEEK(date_format(addedTime,'%Y-%m-%d')) = YEARWEEK(now())-1; -- 查询上个月的数据 select fullName,addedTime FROM t_user where date_format(addedTime,'%Y-%m')=date_format(DATE_SUB(curdate(), INTERVAL 1 MONTH),'%Y-%m'); -- 查询当前月份的数据 select fullName,addedTime FROM t_user where DATE_FORMAT(addedTime,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m'); select fullName,addedTime FROM t_user where date_format(addedTime,'%Y-%m')=date_format(now(),'%Y-%m'); -- 查询指定时间段的数据 select fullName,addedTime FROM t_user where addedTime between '2017-1-1 00:00:00' and '2018-1-1 00:00:00'; select fullName,addedTime FROM t_user where addedTime >='2017-1-1 00:00:00' and addedTime < '2018-1-1 00:00:00';
https://www.cnblogs.com/kenx/p/15211450.html
故乡明