MySQL里获取当前week、month、quarter,以及date(),date_format()和str_to_date(),DATEDIFF()操作 - Go语言中文社区

MySQL里获取当前week、month、quarter,以及date(),date_format()和str_to_date(),DATEDIFF()操作


查询某年的数据

  • 查询某年的数据
 select * from oa_item_info where created like '2018-%';

select * from oa_item_info where left(created,4)='2018';

select * from oa_item_info where year(created)='2018';
  • 今年的数据:
select * from oa_item_info where year(created)=year(now());
  • 上一年的数据:
select * from oa_item_info where year(created)=year(date_sub(now(),interval 1 year));

在这里插入图片描述

查询某季度的数据

select QUARTER(created)  as quartername ,created from oa_item_info ;

先看一下quarter函数返回的数据,第一列是quartername,第二列是created

1-3月返回1,4-6月返回2,7到9月返回3,10到12月返回4
在这里插入图片描述
并不是搜索本季度的数据:

select * from oa_item_info where QUARTER(created)=QUARTER(now());

这条sql语句返回的是所有年份,当前季度的数据,比如现在是4月,会把所有年份4到6月的数据都检索出来

搜索本季度的数据:

加上本年的限制条件

 select * from oa_item_info where QUARTER(created)=QUARTER(now()) and year(created)=year(now());

查询某月的数据

 select month(created) as monthname,created from oa_item_info;

看一下返回数据:第一列是monthname,第二列是created
在这里插入图片描述
所有年份2月的数据

 select * from oa_item_info where month(created)=2

加上年份的限定条件就可以了

查询某周的数据

select week(created) as weekname,created from oa_item_info ;

看一下返回数据:第一列是weekname,第二列是created

返回的是一年中的第几周
在这里插入图片描述
本周的数据:

 select  created   from oa_item_info where week(created)=week(now()) and year(created)=year(now());

select * from oa_item_info where YEARWEEK(date_format(created,'%Y-%m-%d')) = YEARWEEK(now())

看一下week和yearweek的区别:

数据库中加入两条周数一致的日期:
在这里插入图片描述
看一下yearweek的返回值:
在这里插入图片描述
看一下搜索结果:

select  created   from oa_item_info where week(created)=week(now());

week把两条年份不一样的都搜出来了
在这里插入图片描述

 select created  from oa_item_info where YEARWEEK(date_format(created,'%Y-%m-%d')) = YEARWEEK(now()) ;

select created  from oa_item_info where YEARWEEK(created) = YEARWEEK(now()) ;

不用date_format函数也可以

yearweek只搜出了今天的
在这里插入图片描述


未完

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/zhizhengguan/article/details/104512210
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢