一、基本概念
- 调用方式:
select 函数名(实参列表) from 表
- 重点学习内容:函数名称、函数实现的功能
二、分类
- 单行函数:如 ifnull、length、concat,传入一个值返回一个值,详细点说就是你在查询过程中在 select 后面调用了单行函数,在里面传入了某个字段,那么查询结果的显示就会是该字段在经过了单行函数处理后的结果。
- 分组函数:count、max、min、avg、sum,传入一组值返回一组值。
这里我们重点学习单行函数,下面介绍的都是单行函数。
三、字符函数
函数 | 作用 |
---|
length | 用于获取参数值的字节个数(与 MySQL 设置的字符集有关) |
concat | 拼接字符串 |
upper、lower | 将传入的单词变为大写、小写 |
substr | 截取传入字符串的字串 |
instr | 返回子串在母串中第一次出现的索引 |
trim | 去处字符串前后空格 |
lpad、rpad | 左、右填充字符串到指定长度 |
replace | 替换字符串中指定子串为新的子串 |
- length
select ename as '姓名', length(ename) as '姓名字节个数' from emp;
- concat
select concat(last_name, '_', first_name) as '姓名' from people;
- upper、lower
select concat(upper(last_name), '_', lower(first_name)) as '姓名' from people;
- substr
select substr('莫莫喜欢吃冰淇淋', 6, 3);
select substr('莫莫喜欢吃冰淇淋', 6);
- 综合案例
select concat(substr(last_name, 1, 1), '_', substr(concat(last_name, first_name), 2)) from people;
- instr
select instr('莫莫喜欢吃冰淇淋', '喜欢');
- trim
select trim(' 速冻莫莫 ');
select trim('a' from 'aaaaaaaa速冻莫莫aaaaaaaaaaa' );
- lpad、rpad
select lpad('莫莫', 5, '*');
select rpad('莫莫', 5, '*');
- replace
select replace('莫莫喜欢吃冰淇淋', '冰淇淋', '榴莲');
四、数学函数
函数 | 作用 |
---|
round | 四舍五入为整数 |
ceil、floor | 向上、向下取整 |
truncate | 强制保留指定位数小数 |
mod | 取余数 |
- round
select round(3.656);
select round(3.656, 2);
- ceil、floor
select ceil(1.002);
select floor(0.9);
- truncate
select truncate(11.3729, 2);
- mod
select mod(10, 3);
五、日期函数
函数 | 作用 |
---|
now | 返回当前系统日期 + 时间 |
curdate | 返回当前系统日期 |
curtime | 返回当前系统时间 |
year、month、day … | 获取当前日期数据类型数据的年、月、日… |
- now
select now();
- curdate
select curdate();
- curtime
select curtime();
- year、month、day、hour、minute、second
select year('2019-01-01 10:12:32');
select month('2019-01-01 10:12:32');
select month('2019-01-01 10:12:32');
select hour('2019-01-01 10:12:32');
select minute('2019-01-01 10:12:32');
select second('2019-01-01 10:12:32');
六、流程控制函数
- if
select if(3 > 1, '3大于1', '3不大于1');
- case
case 要判断的字段或表达式
when 常量1 then 要显示的值1或语句1
when 常量2 then 要显示的值2或语句2
...
else 要显示的值n或语句n;
end
select salary oldsal, deptno,
case deptno
when 10 then oldsal * 1.1
when 20 then oldsal * 1.2
when 30 then oldsal * 1.3
else oldsal
end as newsal
from emp;
case
when 条件1 then 要显示的值1或语句1
when 条件2 then 要显示的值2或语句2
...
else 要显示的值n或语句n
end
select salary,
case
when salary > 20000 then 'A'
when salary > 15000 then 'B'
when salary > 10000 then 'C'
else 'D'
end as '工资级别'
from emp;