1.查询当天数据

第一种:数量小的时候用,数据量稍微起来巨慢

select 字段 from 表名 where to_days(时间字段) = to_days(now());

第二种:速度快

select 字段 from 表名 where 时间字段 BETWEEN CONCAT(CURDATE(),' 00:00:00') AND CONCAT(CURDATE(),' 23:59:59');

最好配合复合索引来查,避免全表扫描

2.查询昨天的数据

SELECT * FROM `day_sell` WHERE TO_DAYS(NOW()) - TO_DAYS(sell_time) <= 1

3.查询最近7天的(包含7天总计7天)

#7天的数据SELECT * FROM `day_sell` WHERE DATE_SUB(CURDATE(),INTERVAL 7 DAY) < DATE(sell_time); SELECT * FROM day_sell WHERE YEARWEEK(DATE_FORMAT(sell_time,'%Y-%m-%d')) = YEARWEEK(NOW()); #上周的数据SELECT * FROM day_sell WHERE YEARWEEK(DATE_FORMAT(sell_time,'%Y-%m-%d')) = YEARWEEK(NOW()) -1;

4.查询本月的数据

SELECT * FROM `day_sell` WHERE DATE_FORMAT(sell_time,'%Y-%m')= DATE_FORMAT(CURDATE(),'%Y-%m')

5.查询上个月的数据

SELECT * FROM day_sell WHERE PERIOD_DIFF(DATE_FORMAT(NOW(),'%Y%m'),DATE_FORMAT(sell_time,'%Y%m')) = 1;

6.查询上季度

SELECT * FROM day_sell WHERE QUARTER(sell_time) = QUARTER(DATE_SUB(NOW(),INTERVAL 1 QUARTER));

7.查询本季度

SELECT * FROM `day_sell` WHERE QUARTER(sell_time) = QUARTER(NOW())

8.查询今年的数据

SELECT * FROM `day_sell` WHERE YEAR(sell_time) = YEAR(NOW())

9.计算两个时间间隔-天

SELECT DATEDIFF('2020-10-29','2020-10-28') AS days;

10.按周统计

SELECT DATE_FORMAT(sell_time,'%Y%u') weeks,COUNT(sell_time) COUNT FROM `day_sell` GROUP BY weeks;

11.按天统计

SELECT DATE_FORMAT(sell_time,'%Y%m%d') days,COUNT(sell_time) COUNT FROM day_sell GROUP BY days;

12.按月统计

SELECT DATE_FORMAT(sell_time,'%Y%m') months,COUNT(sell_time) COUNT FROM day_sell GROUP BY months;

13.查询去年

SELECT * FROM day_sell WHERE YEAR(sell_time) = YEAR(DATE_SUB(NOW(),INTERVAL 1 YEAR));

14.查询近6个月的数据

SELECT * FROM day_sell WHERE sell_time BETWEEN DATE_SUB(NOW(),INTERVAL 6 MONTH) AND NOW();