Mysql資料庫查詢技巧 日期

2021-10-23 16:32:31 字數 1631 閱讀 7342

1.mysql按日,按月,按年,按周分組統計資料

#按日查詢

select date_format(time,'%y-%m-%d') thetime, sum(score) from timi group by thetime;
#按月查詢

select date_format(time,'%y-%m') thetime, sum(score) from timi group by thetime;
#按年查詢

select date_format(time,'%y') thetime, sum(score) from timi group by thetime;
#按周查詢

select date_format(time,'%y-%u') thetime, sum(score) from timi group by thetime;
2.日期函式

select thetime,date(thetime),year(thetime),month(thetime) from timi where date(thetime) = '2020-08-22';
date('2020-08-22 17:20:02') : 獲取年月日--->2020-08-22

year('2020-08-22 17:20:02') : 獲取年--->2020

month('2020-08-22 17:20:02') : 獲取月--->8

dayofweek('2020-08-22 17:20:02') : 返回日期date的星期索引(1=星期天,2=星期一, ……7=星期六)--->7

weekday('2020-08-22 17:20:02') : 返回date的星期索引(0=星期一,1=星期二, ……6= 星期天)--->5

dayofmonth('2020-08-22 17:20:02') : 返回date的月份中日期,在1到31範圍內--->22

dayofyear('2020-08-22 17:20:02') : 返回date在一年中的日數, 在1到366範圍內 --->235

dayname('2020-08-22 17:20:02') : 返回date的星期名字--->saturday

monthname('2020-08-22 17:20:02') : 返回date的月份名字--->august

quarter('2020-08-22 17:20:02') : 返回date一年中的季度,範圍1到4--->3

3.查詢2023年1月份資料

select * from product where date(add_time) between '2013-01-01' and '2013-01-31';
4.選擇30天內的資料

select something from table where to_days(now()) - to_days(thetime) <= 30;
參考:

感謝:感謝:

資料庫查詢優化技巧 MySQL

在資料庫程式的開發中,效能是最讓人關心和擔心的問題之一,而影響到其效能的乙個關鍵因素就是查詢效率,往往查詢效率的瓶頸都集中在大量耗時的sql語句上。以下就將列舉一些mysql中行之有效的查詢優化手法和準則 1.只要能滿足你的需求,應盡可能使用更小的資料型別 例如使用mediumint代替int。2....

資料庫日期查詢

有表a,日期字段,週期字段 週期欄位為一年,兩年,三年 現要查詢 當前時間是否大於 日期字段 oracle 中執行sql 語句如下 ds cycle 週期字段,為字典值,配置項,值為月份 一年12個月 select from t relay protection t where add months...

資料庫日期範圍查詢

面試遇到了日期範圍的問題,問題基本很簡單,記錄下 查詢在三十天內建立的所有人員 select from tablename t where to char t.create date,yyyymmdd to char sysdate 30,yyyymmdd 獲得當前日期的前三個月 select ad...