MySQL常見的函式
阿新 • • 發佈:2020-12-07
MySQL常見的函式
1. 常見的字元函式
-- concat:拼接字串 select concat(first_name,'_',last_name) from employees; -- length:獲取字串的位元組長度 select length('你好,各位,hello'); -- upper:小寫轉換成大寫 select upper('john'); -- lower:大寫轉換成小寫 select lower('HELLO'); -- char_length:獲取字串長度 select char_length('hello,世界'); -- substr:擷取字串 -- sql 語言中的索引都是從1開始 select substr('hello,world!',7); -- instr:獲取字串中子串第一次出現的索引 select instr('hello,world!','wo'); -- trim:去除字串中前後的無效字元,預設無效字元為空格 select trim(' hello,world! '); select trim('a' from 'aaahello,world!aaa'); -- lpad:用指定的字元左填充字串到指定的長度 select lpad('hello',10,'*'); -- rpad:用指定的字元右填充欄位串到指定的長度 select rpad('hello',10,'*'); -- replace:用指定字元或者字串替換字串中的內容 select replace('hello,world','hello','world');
2. 常見的數學函式
-- 數學函式
-- round:四捨五入
select round(1.65);
select round(1.577,2);
-- ceil:向上取整,返回大於或等於該引數的最大整數
select ceil(1.00);
-- floor:向下取整,返回小於或等於該引數的最大整數
select floor(9.09);
-- truncate:截斷引數資料,不進行四捨五入
select truncate(1.488,2);
-- mod:取餘函式,結果為a-a/b*b
select mod(10,3);
3. 常見的日期函式
-- 日期函式 -- now:返回當前系統日期和時間 select now(); -- curdate:返回當前系統的日期,不包含時間 select curdate(); -- curtime:返回當前系統的時間,不包含日期 select curtime(); -- 獲取日期的指定部分:年/月/日/小時/分鐘/秒 select year(now()) 年, month(now()) 月, day(now()) 日, hour(now()) 時, minute(now()) 分, second(now()) 秒; select monthname(now()); -- str_to_date:將日期格式的字元轉換成指定格式的日期 select str_to_date('2020-10-01','%Y-%m-%d'); -- date_format:將日期轉換為字元 select date_format('2020-10-01','%Y年%c月%d日'); -- datediff:兩個日期之間相隔的天數 select datediff(now(), '1998-08-02');
4. 其他函式
-- version:查詢 MySQL 的版本
select version();
-- database:查詢目前正在使用的資料庫
select database();
-- user:查詢目前登入的使用者
select user();
5. 流程控制函式
-- 流程控制函式 -- if函式:if-else的效果 select if(10>5,'大','小'); -- case函式:①類似於Java中的switch case的效果;②類似於多重if /* case 要判斷的欄位或者表示式 when 常量1 then 值1或者語句1; when 常量2 then 值1或者語句2; ... else 預設值或者預設的語句; end */ select salary 原始工資, department_id, case department_id when 30 then salary*1.1 when 40 then salary*1.2 when 50 then salary*1.3 else salary end 新工資 from employees; /* case when 條件1 then 值1或者語句1; when 條件2 then 值2或者語句2; ... else 預設的值或者預設的語句; end */ select salary 原始工資, case when salary>20000 then 'A' when salary>15000 then 'B' when salary>10000 then 'C' else 'D' end 工資級別 from employees;
6. 分組函式
-- 分組函式:用作統計使用,又稱為聚合函式或者統計函式
-- 分類:sum(求和函式),avg(平均值函式),max(最大值),min(最小值),count(計算個數)
select sum(salary),avg(salary),max(salary),min(salary),count(salary) from employees;
-- 引數支援的型別
-- sum/avg:支援數值型別
-- max/min/count:支援任何型別
-- sum/avg/max/min/count:忽略NULL值進行計算
-- 分組函式和distinct配合使用可以對資料去重
select sum(distinct salary), sum(salary) from employees;
select count(distinct salary), count(salary) from employees;
-- count函式
-- 對於MYISAM引擎:count(*)效率較高
-- 對於INNDB引擎,count(*)和count(1)的效率差不多,但是比count(欄位)效率高
-- 和分組函式一同查詢的欄位只能是group by後的欄位