MySql 针对日期的一些计算/查询操作
废话不多说,直接上干货
-- 今天 SELECT * FROM t_user_info WHERE TO_DAYS(create_time) = TO_DAYS(NOW());
结果:
-- 昨天
SELECT * FROM t_user_info WHERE TO_DAYS( NOW( ) ) - TO_DAYS( create_time) = 1;
结果:
-- 近7天
SELECT * FROM t_user_info WHERE DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= DATE(create_time);
结果:
-- 近30天
SELECT * FROM t_user_info WHERE DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= DATE(create_time);
结果:
-- 本月
SELECT * FROM t_user_info WHERE DATE_FORMAT( create_time, '%Y%m' ) = DATE_FORMAT( CURDATE() , '%Y%m' );
-- 查询当前月份的数据
SELECT * FROM t_user_info WHERE DATE_FORMAT(create_time,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m');
结果:
-- 上一月
SELECT * FROM t_user_info WHERE PERIOD_DIFF( DATE_FORMAT( NOW() , '%Y%m' ) , DATE_FORMAT( create_time, '%Y%m' ) ) =1;
-- 查询上个月的数据
SELECT * FROM t_user_info WHERE DATE_FORMAT(create_time,'%Y-%m') = DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 1 MONTH),'%Y-%m');
结果:
-- 查询当前这周的数据
SELECT * FROM t_user_info WHERE YEARWEEK(DATE_FORMAT(create_time,'%Y-%m-%d')) = YEARWEEK(NOW());
结果:
-- 查询上周的数据
SELECT * FROM t_user_info WHERE YEARWEEK(DATE_FORMAT(create_time,'%Y-%m-%d')) = YEARWEEK(NOW())-1;
结果:
-- 查询本季度数据
SELECT * FROM t_user_info WHERE QUARTER(create_time)=QUARTER(NOW());
-- 查询上季度数据
SELECT * FROM t_user_info WHERE QUARTER(create_time)=QUARTER(DATE_SUB(NOW(),INTERVAL 1 QUARTER));
-- 查询本年数据
SELECT * FROM t_user_info WHERE YEAR(create_time)=YEAR(NOW());
未完待续......