SQL常用函數
1、字符串函數
函數調用的語法:select 函數(參數);
常用的字符串函數有:
拼接字符串,將幾個字符串拼到一起:concat (s1,s2,……);
select concat('你好','hello');
update mytable set wherefo = concat('中國',wherefo);
將所有字符轉換為大寫:upper(字符串);
select upper('hello')
將所有字符轉換為小寫::lower(字符串);
select lower('HELLO');
使用指定的字符對字符串左填充到指定長度:lpad(字符串,長度,填充字符);
select lpad('01',5,'*');
update mytable set number= lpad(number,10,'0');
使用指定的字符對字符串右填充到指定長度:rpad(字符串,長度,填充字符);
select rpad('01',5,'*');
去除字符串頭尾的空格:trim(字符串)
select trim(' hello ');
返回從指定位置出發長度為n的字符串子串:substring(string,start,len);
select substring('hellohello',1,5);
update mytable set number = substring(number,5,6)
2、數值函數
常見的數值函數有
對x向上取整,取大于x的最小整數:ceil(x)
select ceil(1.2);
對x向下取整,取小于x的最大整數:floor(x)
select floor(1.9);
取x/y的模,x除以y的余數:mod(x,y)
select mod(5,4);
生成0-1之間的隨機數:rand()
#隨機生成六位數驗證碼
select lpad((round(rand(),6))*1000000,6,(round(rand(),1)*10));
取x四舍五入后保留y位的數:round(x,y)
select round(3.14159,2)
3、日期函數
返回當前日期:curdate()
select curdate();
返回當前時間:curtime()
select curtime();
返回當前日期與時間:now()
select now();
獲取指定date的年份:year(date)
select year('2025-3-3');
獲取指定date的月份:month(date)
select month('2025-3-3');
獲取指定date的日期:day(date)
select day('2025-3-3');
返回date加指定時間exp的類型后的date:date_add(date,interval exp type)
select date_add('2025-3-3',interval 70 day);
返回date1與date2相差的時間:datediff(date1,date2)
select datediff(curdate(),'2025-3-3')
select name as ‘姓名’,datediff(curdate(),dates) as '入學天數' from mytable order by '入學天數','姓名';
4、流程函數
判斷value值,若為ture,則返回值1,若為false,則返回值2:if(value,值1,值2)
select name as '姓名' ,if(wherefo='中國北京','是','否') as '是否北京' from mytable;
判斷值1的值,若值1不為null,則返回值1,否則返回值2:ifnull(值1,值2)
select ifnull(null,1);
若value1為ture,則返回值1,若value2為ture,則返回值2……否則返回default:case when value1 then 值1 when? value2 then 值2 ……else default end
selectname as '姓名',(case when score >=560 then '優秀'when score >=520 then '良好'when score >=480 then '及格'else '不及格'end) as '成績情況'
from mytable;
判斷exp的值,若為value1,則返回值1……否則返回default:case exp when value1 then 值1……else default end
select name as '姓名',(case wherefowhen '中國北京' then '一線城市'when '中國上海' then '一線城市'else '其他城市'end) as '居住情況'
from mytable;