共計 1251 個字符,預計需要花費 4 分鐘才能閱讀完成。
自動寫代碼機器人,免費開通
本篇文章給大家分享的是有關如何在 mysql 中使用日期處理函數,丸趣 TV 小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著丸趣 TV 小編一起來看看吧。
首先創建一張實驗用的一張表
drop table if exists t_student;
create table t_student(
id int primary key auto_increment,
name varchar(20) not null comment 姓名 ,
birthday date comment 生日
)Engine=InnoDB default charset utf8;
insert into t_student values(null, tom , 1992-02-03
insert into t_student values(null, jerry , 1993-02-06
insert into t_student values(null, hank , 1993-03-05
insert into t_student values(null, xiaoming ,now());
其中 date 類型 是記錄 mysql 精確日期的類型
now() 函數
獲取當前時間
year() , month(),dayofmonth()
上面三個函數是分別從一個日期或者時間中提取出年,月,日
比如 想得到生日為 2 月份的學生
select * from t_student where month(birthday) = 2;
monthname() 函數
輸出個月份的英文單詞
select monthname(birthday) from t_student;
timestampdiff() 函數
比較兩個日期間的差值
例:學生的年齡
select timestampdiff(year,birthday ,now()) as age from t_student;
timestampdiff 函數的第一個參數為 計算結果的單位:有 year(年) month(月),day(日) 等等。
to_days()
將日期轉換成天數
計算兩個時間的天數, 同 timestampdiff(day,arg1,arg2) 是一個道理。
查詢生日小于當前日期 60 以內的學生
select * from t_student where (to_days(now()) – to_days(birthday))
date_add 和 date_sub
根據一個日期,計算出另一個日期,date_add 是加上 date_sub 是減去
select date_add(1970-1-1 , interval 10 year); # 1970 年 加上 10 年
select date_sub(1970-1-1 , interval 10 year); #1970 年減去 10 年
以上就是如何在 mysql 中使用日期處理函數,丸趣 TV 小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注丸趣 TV 行業資訊頻道。
向 AI 問一下細節