1.单行函数
1.1字符函数(字符串)
length
- 获取参数值的字节个数(一个汉字三个字节)
- select length(‘Grace’);
concat 拼接字符串
select concat(last_name,’_’,first_name) 姓名 from employees;
upper、lower 大小写
select upper(‘mei’);
substr、substring
select substr(‘李莫愁爱陆展元’, 5);
select substr(‘李莫愁爱陆展元’, 1,3);
instr
返回子串第一次出现的索引,找不到返回0
trim
去掉前后空格,
去掉指定字符串,只去除前后
select trim(‘a’ from ‘aaaaaa孙aaaaa悟空aaaaa’) output;
lpad 、rpad
用指定的字符左/右填充指定长度
replace 替换
select replace(‘孙悟空孙悟空’, ‘孙悟空’, ‘猪八戒’) output;
1.2 数学函数
round 四舍五入
select round(1.3); #1
select round(1.33, 1);#1.3
ceil 向上取整,返回>=该参数的最小整数
select ceil(1.334); #2
floor 向下取整,返回<=该参数的最大整数
select floor(1.334);#1
truncate 截断
小数点后的位数
select truncate(1.334, 2); #1.33
mod 取余
select mod(10,-3); #1
1.3 日期函数
now 返回当前系统的日期+时间
select now();
curdate 返回当前日期,不包含时间
select curdate();
curtime 返回当前时间,不包含日期
select curtime();
获取指定的部分,年,月,日,小时,分钟,秒
select year(now()) 年;
str_to_date
将日期格式的字符转换成指定格式的日期
select str_to_date(‘1-4-2020’, ‘%m-%d-%Y’);
2020-4-1
date_format
将日期转换成字符
select date_format(‘2020/7/28’, ‘%Y年%m月%d日’);
2020年7月28日
1.4 其他函数
version 版本号
select version();
5.7.17
database
select database();
user
select user();
root@localhost
1.5 流程控制函数
if函数
select if(10<5,‘大’,‘小’);
select last_name, commission_pct, IF(commission_pct is null,‘没奖金’,‘有奖金’) 备注 from employees;
case - when - then- end要判断的字段或表达式
- 字段:select salary, department_id,
CASE department_id
WHEN 30 THEN salary * 1.1
WHEN 40 THEN salary * 1.3
ELSE salary
END AS 新工资 from employees; - 条件:select salary,department_id,
CASE
When salary > 20000 THEN ‘A’
When salary > 15000 THEN ‘B’
When salary > 10000 THEN ‘C’
ELSE ‘D’
END AS 工资级别 from employees;