1. 程式人生 > 其它 >MySQL 常用函式 流程控制

MySQL 常用函式 流程控制

單行函式

1. 單行函式

字元函式
-- length()獲取長度

-- lower() 轉小寫

-- upper()轉大寫

-- 左填充 lpad()

-- 右填充 rpad()

-- 去掉左右兩次的空格 trim()

-- 擷取字串substring() 索引從1開始

-- concat() 字串的拼接
    

    ## 字元函式
select length(first_name),first_name from employees;

select upper(first_name) from employees;

select lower(first_name) from employees;

## 左填充
select LPAD(last_name,10,'x')  from employees;

##右填充
select RPAD(last_name,10,'x')  from employees;

#去除空格  ltrim  rtrim  trim
select ltrim('   abc'),'   abc';
select rtrim('abc    '),'abc    ';
select trim('      abc    '),'    abc    ';

select trim('abc'),'abc';


#擷取字串  字元初始位置從1開始
#SUBSTRING(str,pos,len)    str 表示需要擷取的字串  pos 擷取起始位置 len 擷取的長度
select SUBSTRING(last_name,2,1) from employees;
select SUBSTR(last_name,2,1) from employees;

select CONCAT('瘋狂','的','石頭');

案例:
案例1: 查詢員工的姓名,將姓名拼接起來,顯示在一個欄位下 
first_name  last_name
select concat(first_name,last_name) as 姓名 from employees;
數學函式 
-- ceil() 向上取整

-- floor() 向下取整


-- round() 四捨五入


-- 取絕對值abs()

-- rand()生成隨機數 [0,1)

select ceil(3.456);

select floor(3.456);

select round(3.556);

select abs(-1);

select RAND();



日期函式
-- 獲取當前時間  日期+時間 now()

-- 獲取年月日  year() month() day()

-- 獲取當前日期

-- 獲取當前時間

#獲取當前系統時間
select now();  # 年月日 時分秒
select YEAR(now());  #提取所傳時間的 year部分
select month(now()); #提取所傳時間的 month
select day(now());   #提取所傳時間的 day
select DATE(now());  #提取所傳時間的 年月日部分
select TIME(now());  #提取所傳時間的 時分秒部分

#流程控制解構
1.if();
2.  case 
	when 條件表示式 then 值或者表示式
	when 條件表示式 then 值或者表示式
	...
	else 值或者表示式
	end  
	(相當於  if()...else if()...else if()... else )結構
	
案例2:查詢員工的薪資和姓名,如果薪資大於10000,是一個高階員工,小於等於10000初級員工
select salary,last_name,
IF(salary>10000,'高階員工','初級員工') as 級別
from employees;


案例3:查詢員工的舊薪資和姓名,新薪資,如果部門id>100 薪資顯示 3倍,如果部門id>50薪資顯示2倍,如果部門id>30 薪資不變,如果部門id <30 薪資減半.

select salary,last_name,
case 
	when department_id > 100 then salary*3
	when department_id > 50 then salary*2
	when department_id > 30 then salary
	else  salary/2
	end  as 新薪資
from employees

  

多行函式(分組函式)

常見的分組函式
sum(欄位):求該欄位的所有值的和
avg(欄位):求該欄位的平均值
max(欄位):求最大值
min(欄位):求最小值
count[欄位):計算該欄位中非空的值的個數

程式碼

#案例1:查詢有獎金的員工的平均工資
select avg(salary) as 有獎金的員工的平均薪資 from employees 
where commission_pct is not null;

#案例2:查詢年薪的平均值
#年薪 = (薪資+獎金)*12
select avg(  (salary+ ifnull(commission_pct,0))*12  ) as 年薪平均值 
from employees;

#案例3 統計員工數量 使用count統計數量時,優先選擇 主鍵
select count(employee_id) from employees;


#案例4 分別統計每個工作的員工數量
#分組後 顯示字句中 一般只會顯示分組欄位,以及分組函式,其他欄位沒有意義
select job_id,count(job_id) from employees group by job_id;

#案例5 分別統計每個部門的員工數量
select department_id,count(employee_id) from employees group by department_id;

#案例6 查詢最低工資都比5000高的工作
select job_id,min(salary) 工作最低薪資 from employees 
group by job_id having min(salary) > 5000;


# where 分組前過濾  行過濾,where 不支援分組函式
# having 分組後過濾 組過濾,having 支援分組函式

#目前為止的查詢關鍵字 where,having,group by,select,from,order by
#這些關鍵字存在書寫順序,執行順序
#select -> from - > where -> group by -> having -> order by