MySQL笔记常见函数
一.单行函数:
1.upper():转换成大写
2.lower(): 转换成小写
3.substr(): 截取子串
1.截取从指定索引处开始后面所有字符
select substr('李莫愁爱上了陆展元', 7);---->陆展元
2.截取从指定索引处指定字符长度的字符
select substr('李莫愁爱上了陆展元', 1, 3); ---->李莫愁
案例:姓名中首字符大写,其他字符小写然后用_拼接,显示出来
select concat(upper(substr(last_name, 1,1)),'_', lower(substr(last_name, 2))) from employees;
4.instr(): 返回子串第一次出现的索引
select instr('abcdefg', 'cde');--->3(mysql中索引从1开始)
5.trim():去前后空格或去前后指定字符串
select length(trim(' 张翠山 ')) as out_put;---> 张翠山
select trim('aa', from 'aaaaaaaaa张aaaaaaa翠山aaaaaaaaa') as out_put;
---->张aaaaaaa翠山
6.lpad():用指定的字符实现左填充到指定长度(此时说的长 度是字符个数)
select lpad('殷素素',2,'*') ;-----> 殷素
7.rapd():用指定的字符实现右填充到指定长度
select rpad('殷素素', 12,'ab');-----> 殷素素ababababa
8.replace():替换
select replace('周芷若周芷若周芷若张无忌爱上了周芷若','周芷若','赵敏');
----> 赵敏赵敏赵敏张无忌爱上了赵敏
二.数学函数
1.round 四舍五入
select round(-1.55); ---> -2
select round(1.567, 2); ---> 1.57
2.ceil():向上取整,返回>=该参数的最小整数
select ceil(-1.02); --> -1
3.floor():向下取整,返回<=该参数的最大整数
select floor(-9.99); ---> -10
4.truncate():截断
select truncate(1.69999, 1); ----> 1.6
5.mod():取余
select mod(10, 3); ---> 1
select 10%3; ---> 1
三.日期函数
1.now():返回当前系统日期+时间
select now();
2.curdate():返回当前系统日期,不包含时间
select curdate();
3.curtime():返回当前时间,不包含日期
select curtime();
4.可以获取指定的部分,年,月,日,小时,分钟,秒
select year(now()) 年;
select year('1998-1-1') 年;
select year(hiredate) 年 from employees;
select month(now()) 月;
select monthname(now()) 月;
5.str_to_date:将日期格式的字符转换成指定格式的日期
STR_TO_DATE('9-13-1999','%m-%d-%Y');----> 1999-09-13
6.date_format:将日期转换成字符
DATE_FORMAT('2018/6/6', '%Y年%m月%d日'); --->2018年06月06日
案例:
str_to_date:
1.select str_to_date('1998-3-2','%Y-%c-%d'); --->1998-03-02
2.查询入职日期为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');
date_format:
1.select date(now(), '%y年%m月%d日');
2.查询有奖金的员工名和入职日期(xx月/xx日 xx年)
select last_name, date_format(hiredate, '%m月/%d日 %y年')
from employees
where commission_pct is not null;
四.其他函数
version(): mysql版本号
datebase():当前数据库名
user():返回MySQL连接的当前用户名和主机名
五.流程控制函数
if函数
语法:
if(表达式,表达式1,表达式2)
如果表达式的值为真,返回表达式1,否则返回表达式2
案例
select if(10<5, '大', '小'); ->小
select last_name, commission_pct, if(commission_pct is not null,'没奖金,呵呵','有奖金,嘻嘻');
case函数使用一:相当于java中的swith
语法:
case 要判断的字段或表达式
when 常量1 then 要显示的值1或语句1;
when 常量2 then 要显示的值2或语句2;
......
else 要显示的值n或语句n;
end
案例:
case函数使用二:相当于java中的if..else if..else if..else
语法:
case
when 条件1 then 要显示的值1或语句1
when 条件2 then 要显示的值2或语句2
...
else 要显示的值n或语句n
end
六.分组函数
功能:用作统计使用,又称为聚合函数或统计函数或组函数
分类:sum 求和,avg 平均值, max 最大值, min 最小值, count 计算个数