前言:
正文:
select * from table where created like '2018-%'; select * from table where left(created, 4) = '2018'; select * from table where year(created) = '2018';
今年的数据
select * from table where year(created) = year(now());
前一年的数据
select * from table where year(created) = year(date_sub(now(), interval 1 year));
QUARTER() :1-3月返回1,4-6月返回2,7到9月返回3,10到12月返回4
本季度的数据
select * from table where quarter(created) = quarter(now()) and year(created) = year(now());
MONTH():1~12
当月的数据
select * from table where month(created) = month(now());
WEEK()和YEARWEEK()的区别:week只是周数(如:16),yearweek还有年份的信息(如:201816)
本周的数据
select * from table where week(created)= week(now()) and year(created)= year(now()); select * from table where yearweek(date_format(created,'%Y-%m-%d')) = yearweek(now());
上一周的数据:
select * from table where yearweek(date_format(created, '%Y-%m-%d')) = yearweek(now())-1;
注意:它们默认都是从周日开始算的,需要从周一开始计算时,需要加入第二个参数1—— week(created,1)
TO_DAYS():返回从0年开始的天数
FROM_DAYS():根据天数,返回日期
今天的数据
select * from table where to_days(created) = to_days(now());
昨天的数据
select * from table where to_days(now()) - to_days(created) = 1;
参考博客:
Mysql 查询某年,某季度,某月,某天搜索方法总结 - 错题集 - 优快云博客
https://blog.youkuaiyun.com/ymk0375/article/details/80059395
本文详细介绍如何使用MySQL查询特定时间范围内的数据,包括某年、某季度、某月、某周和某天的数据检索方法。通过具体SQL语句示例,如使用YEAR(), QUARTER(), MONTH(), WEEK(), TO_DAYS()等函数,帮助读者掌握精确的时间筛选技巧。
741

被折叠的 条评论
为什么被折叠?



