【MySQL】【10】查询某年,某季度,某月,某周,某天的数据

前言:

1,某年

2,某季度

3,某月

4,某周

5,某天

正文:

1,某年

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));

2,某季度

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());

3,某月

MONTH():1~12

当月的数据

select * from table where month(created) = month(now());

4,某周

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)

5,某天

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 查询某年,某季度,某月,某天搜索方法总结 - 错题集 - CSDN博客
https://blog.csdn.net/ymk0375/article/details/80059395

 

posted @ 2019-08-20 21:39  花生喂龙  阅读(699)  评论(0编辑  收藏  举报