MySQL-常见函数

常见函数

image

length()

image

concat 拼接字符串

image

upper(大写)、lower(小写)

image

案例:将姓变大写,名变小写,然后拼接

select concat(upper(last_name),'_',lower(first_name)) 姓名
from employees;

image

substr、substring

#substr、substring
注意:索引从1开始
#哉取从指定索引处后面所有字符
SELECT SUBSTR('李莫愁爱上了陆展元',7) out_put;
#截取从指定索引处指定字符长度的字符
SELect SUBSTR('李莫愁爱上了陆展元',1,3) out_put;

image

案例:姓名中首字符大写,其他字符小写然后用_拼接,显示出来

#案例:姓名中首字符大写,其他字符小写然后用_拼接,显示出来
SELECT
         CONCAT(UPPER(SUBSTR(last_name,1,1)),'_',LOWER(SUBSTR(last_name,2))) out_put
FROM 
     employees;

image

instr返回子串第一次出现的索引,如果找不到返回0

#5.instr返回子串第一次出现的索引,如果找不到返回0
SELECT INSTR('杨不殷六侠悔爱上了殷六侠','殷六侠') AS out_put;

image

trim 去前后空格

#trim 去前后空格
SELECT LENGTH(TRIM('   张催生   ')) AS out_put;

SELECT TRIM('a' FROM   'aaaaaaaa张aaaaaaa催生aaaa') AS out_put;

image

lpad用指定的字符实现左填充指定长度

#lpad用指定的字符实现左填充指定长度

SELECT LPAD('殷紊素',10,'*') AS out_put;

image

SELECT LPAD('殷紊素',2,'*') AS out_put;

image

rpad用指定的字符实现右填充指定长度

#rpad用指定的字符实现右填充指定长度

SELECT RPAD('殷紊素',12,'ab') AS out_put;

image

relpace 替换

#relpace 替换

SELECT REPLACE('张无忌爱上了周芷若','周芷若','赵敏') AS out_put;

image

数学函数

round四舍五入

image

ceil 向上取整,返回>=该参数的最小整数

image

floor 向下取整,返回<=该参数的最大整数

image

truncate 截断

image

mod 取余

image

日期函数

image

image

查询入职时间的年

SELECT
       YEAR(`hiredate`) 年 
FROM 
     employees;

image

image

日期格式的符号

image

str_to_date 将字符通过指定的格式转换成日期

#str_to_date 将字符通过指定的格式转换成日期
SELECT STR_TO_DATE('1999-3-2','%Y-%c-%d') AS out_put;

image

查询入职日期为1992-4-3的员工信息

#查询入职日期为1992-4-3的员工信息
select * from employees where hiredate='1992-4-3'

select * from employees where hiredate=str_to_date('4-3 1992','%c-%d %Y');

image

date_format 将日期转成字符

#date_format 将日期转成字符
SELECT DATE_FORMAT(NOW(),'%y年%m月%d日') AS out_put;

image

查询有奖金的员工名和入职日期(xx月/xx日 xx年)

#查询有奖金的员工名和入职日期(xx月/xx日 xx年)
SELECT last_name,DATE_FORMAT(hiredate,'%m月/%d日 %y年') 入职日期
FROM employees
WHERE `commission_pct` IS NOT NULL;

image

其他函数

image

流程控制函数

1.if函数: if else的效果

SELECT IF(10<5,'大','小') 
如果成立则 大 不成立则 小

image

SELECT last_name,commission_pct,IF(commission_pct IS NULL,'没奖金','有奖金') 备注
FROM employees;

image

case函数的使用一:switch case的效果

image

image

案例:查询员工的工资,要求,部门号=30,显示的工资为1.1倍,部门号=40,显示的工资为1.2倍,部门号=50,显示的工资为1.3倍,其他部门,显示的工资为原工资

select salary 原始工资,department_id,
case department_id
when 30 then 1.1*salary
when 40 then 1.2*salary
when 50 then 1.3*salary
else salary
end as 新工资
from employees;

image

case函数的使用二:类似于 多重if

image

image

案例:查询员工的工资的情况,如果工资>20000,显示A级别,如果工资>15000,显示B级别,如果工资>10000,显示c级别,否则,显示D级别

select `salary`,
case
when `salary`>20000 then 'A'    
WHEN `salary`>15000 THEN 'B'   
WHEN `salary`>10000 THEN 'C'   
else 'D'
end as 工资级别
FROM employees;

image

总结:常见函数

image

image

image

习题讲解

image

image

image

image
image

posted @ 2021-06-26 13:06  司砚章  阅读(42)  评论(0)    收藏  举报