日期函數
返回當前日期,只包含年月日 select curdate()
返回當前時間,只包含時分秒 select curtime()
返回當前的日期和時間,年月日時分秒全都包含 select now()
提取具體日期類型
- year() yearweek() ,hour(),month()等等
- select year(now()) as '年',yearweek(now()) as '年,周',hour(now()) as '周',minute(now()) as '小時',
month(now()) '月',monthname(now()) '月名字',dayofmonth(now()) as '當月多少日'
- EXTRACT() 函數用于返回日期/時間的單獨部分,比如年、月、日、小時、分鐘等等。
- (select extract(year from now()),extract(month from now()),extract(day from now()),extract(hour from now()),extract(minute from now()))
日期格式
- DATE_FORMAT(date,fmt)函數:按字符串 fmt 格式化日期 date 值 (select date_format(now(),'%Y-%m-%d'))
日期運算
date_add(date,interval number dateType) example (select date_add(now(),interval 2 year) as 'add 2 year date')
(select date_add(now(),interval -2 hour) as 'add 2')也可以傳入負數即回到過去某個時間date_sub(date,interval number dateType) example (select date_sub(now(),interval 2 year))
datediff(date,date) 計算兩個日期之間相差的天數 (select datediff(now(),date_add(now(),interval 2 month)) as '計算兩個日期之間相差天數')
流程函數
- if 函數
create table salary (userid int,salary decimal(9,2));
insert into salary values(1,1000),(2,2000), (3,3000),(4,4000),(5,5000), (1,null);
- (select if(s.salary>2000,'high','low'),s.salary from salary s)
- IFNULL(value1,value2)函數:這個函數一般用來替換 NULL 值的,我們知道 NULL 值是不能參與數值運算的
- (select ifnull(s.salary,0),s.salary from salary s)當檢測到值的時候用0代替
數值函數
- ABS(x)函數:返回 x 的絕對值
- select abs(-56),abs(round(rand()*10))
- cell(x)函數 返回大于 x 的最大整數值 相當于向上取
- SELECT ceil(0.6),ceiling(0.3),ceil(round(rand()))
- floor()返回小于 x 的最大整數值 相當于向下取
- SELECT floor(0.6),floor(0.3),floor(round(rand()))
- mod(x,y) 返回 x/y 的模
- SELECT mod(5,3)
- rand() 返回 0 到 1 內的隨機值
- ROUND(x,y) 返回參數 x 的四舍五入的有 y 位小數的值
- SELECT round(2.5,3)
- sum()函數
- select sum(f.f_price) as '總價格' from fruits f
字符串函數
- CANCAT(S1,S2,…Sn) 連接 S1,S2,…Sn 為一個字符串
- SELECT concat('hello','wrold'),concat(curdate(),' ',curtime())
- INSERT(str,x,y,instr) 將字符串 str 從第 x 位置開始,y 個字符長的子串替換為字符串 instr(可以用作修改和刪除以及增加)
- SELECT insert('Highlights of Premier Li''s news conference',11,0,'---') 在index=11 取0個字符串替換為xxx
- REPEAT(str,x) 返回 str 重復 x 次的結果
- select REPEAT('Tech aims to help restless sleepers \n',3) 字符串重復3次
- REPLACE(str,a,b)函數:用字符串 b 替換字符串 str 中所有出現的字符串 a。
- select replace('hello_world!','_',' ') 把下劃線替換為空格
- SUBSTRING(str,x,y)函數:返回從字符串 str 中的第 x 位置起 y 個字符長度的字串。此函數經常用來對給定字符串進行字串的提取(ps也可以用作隨機字符串)
- select substring('Century-old folding fan store attracts foreign apprentice',12,8) 截取字符串函數
- length() 獲取字符串長度 select length(''+uuid_short()) as uuidShort , length(uuid()) 這里使用了mysql的uuid