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只搜出了今天的
在這裏插入圖片描述


未完

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章