MySql的常用函数一
调用:select 函数名( 实参列表)from 表 ;
1、单行函数
如 concat、length、iffnull等
一、字符函数
#1.length 获取当前参数值的字节个数
select length(’john') ; //返回4
select length(’张三丰') ; //返回9,一个汉字占3字节,若为gbk编码则一个汉字占2个字节
#2.concat 拼接字符串
select concat(last_name, '_' , first_name) 姓名 from employee
#3.upper、lower 改变大小写
#4.substr、substring 截取字符
select substr('张三丰打死了四时光',7) out_put ; //索引从1开始,则输出的是四时光
select substr('张三丰打死了四时光',1,3) out_put ; //则输出张三丰
#5.instr 返回字串的起始索引
select instr('van爱上了比利王','比利王')as out_put ;
#6.trim 清除中间和前后的空格和多余项
select trim(' 柳桑 ')as out_put;
select trim('a' from 'aaaaaaaaaaaaaaaa柳桑aaaaaaaaaaaa ')as out_put;
#7.lpad 用指定字符左填充,若超过则截断
select lpad('比利王',10,‘*’)as out_put; 左边填充 //输出******比利王
select lpad('比利王',2,‘*’)as out_put; 截断 //输出利王
#8.rpad 用指定字符右填充,若超过则截断
#9.replace 替换
select replace('van打败了比利王','van','魔男') as out_put;
二、数学函数
#round 四舍五入
select round(1.65) ; //输出2
select round(1.567,2) ; //输出1.57 保留两位小数
#ceil 向上取整
select ceil(1.002) ; //输出2
#floor 向下取整,返回<=该参数的最大整数
select floor(-9.99) ; //返回-10
#truncate 截断
select trancate(1.651212,1) ; //返回1.6
#mod 取余 mod(a,b): a-a/b*b
select mod(10,3) ; //返回1
三、日期函数 %Y 四位年 %y 两位年 %m 月份(01,02,03)%c 月份(1,2,3)%d 日(01,02)%H 小时(24小时制)%h小时(12小时制)%i 分钟 %s 秒
#now 返回当前日期+时间
select now( ) ;
#curdate 返回当前系统日期
select curdate( ) ;
#curtime 返回当前时间
select curtime( ) ;
#获取指定的年月日,时分秒 year month(monthname月名) day
select year(now( )) 年 ;
select year('1998-1-1') ;
select year(hiredate) 年 form employee ;
#str_to_date 将日期格式的字符转换成指定格式的日期
select str_to_date('9-13-1999','%m-%d-%y') ; //返回1999-09-13
#date_format 将日期转换成字符
select date_format('2018/6/6','%y年%m月%d日') ; //返回2018年06月06日
四、其它函数
select virson( ) ;查看版本号
select database( ) ;查看当前数据库
select user( ) ;查看当前用户
五、流程控制函数
#1.if函数
select if('10>5','大','小' );输出大,相当于三元运算符
select last_name,commission_pct, if (communission_pct is null,'没奖金','有奖金') 备注
from employee;
#2.case函数的使用一:switch case 的效果
case 要判断的表达式
when 常量1 then 语句1 ;
when 常量2 then 值 ;
...
else 要显示的值n或者语句n ;
select salary 原始工资,department_id
case department_id
when 30 then salary*1.1
when 40 then salary*1.2
else salary
end as 涨后的工资
#case用法2:类似多重if
case
when 条件1 then 显示的值1或者语句1;
when 条件2 then 显示的值2或者语句2;
end

浙公网安备 33010602011771号