在MySQL中内置了很多函数,我们可以通过一段程序或者代码直接调用这个函数
一、字符串函数

下面通过例子来验证这些函数
- -- 字符串函数
-
- -- concat函数
- select concat("hello ","world");
-
- -- lower函数
- select lower("HELLO");
-
- -- upper函数
- select upper("heelo");
-
- -- lpad函数
- select lpad("123",5,'0');
-
- -- rpad函数
- select rpad("123",5,'0');
-
- -- trim函数
- select trim(" hello world ");
-
- -- substring函数
- select substring("1234556789",2,3);
实例说明:
统一一个表的员工工号,不足8位的在前面补0
先查看实例前的员工表

更新字段的值使用updat语句


数值函数
常见的数值函数有

- -- 数值函数
-
- -- ceil函数
- select ceil(4.5);
-
- -- floor函数
- select floor(5.9);
-
- -- mod函数
- select mod(100,2);
-
- -- rand函数
- select rand();
-
- -- round函数
- select round(3.1415926,3);
实例说明
生产一个随机的六位数的验证码


日期函数

- -- 日期函数
-
- -- curdate函数 当前日期
- select curdate();
-
- -- curtime函数 当前时间
- select curtime();
-
- -- now函数 当前日期和时间
- select now();
-
- -- year(date)函数 获取date的年份
- select year(now());
-
- -- month(date)函数 获取date的月份
- select month(now());
-
- -- day(date)函数 获取date的日期
- select day(now());
-
- -- date_add(date,interval expr type)函数 返回一个日期/时间值加上时间间隔expr后的时间值
- select date_add(now(),interval 30 day); -- 30天后
-
- -- datediff(date1,datw2)返回起始时间date1和结束时间date2之间的天数
- select datediff(curdate(),'1949-10-01');
现在有这样一张表

-- 查询所有员工的入职天数,并根据入职天数倒序排序
select name,datediff(curdate(), entrydate) '入职天数' from emp order by '入职天数' desc ;

流程函数

- -- 流程函数
-
- -- if(value,t,f)函数 如果value为true,则返回t,否则返回f
- select if(2>3,2,3);
-
- -- ifnull(value1,value2) 如果value1不为空,返回value1,否则返回value2
- select ifnull(null,'hello');
-
- -- case when [val1] then [res1]...else [default] ebd函数
- -- 如果val1为true,返回res1,... 否则返回default默认值
- select case when 2+3>6 then '正确' else '错误' end;
-
- -- CASE [expr] WHEN [val1] THEN [res1] ... ELSE [ default ] END函数
- -- 如果expr的值等于val1,返回res1,... 否则返回default默认值
- select case 2 WHEN 3 then '对' else '错' end;
流程函数需要结合具体案例来分析使用
接下来,进行一下案例的分析

现在有一张员工表
查询emp表的员工姓名和工作地址 (北京/上海 ----> 一线城市 , 其他 ----> 二线城市)
sql语句怎么书写
select name,case workaddress when '北京' then '一线城市'
when '上海' then '一线城市' else '二线城市' end
as '工作地址' from emp;

例子2
有这样一个分数表

>=85优秀,>=60及格,<60不及格
select name,
case when math>=85 then '优秀' when math>=60 then '及格' else '不及格' end '数学',
case when english>=85 then '优秀' when english>=60 then '及格' else '不及格' end '英语',
case when chinese>=85 then '优秀' when chinese>=60 then '及格' else '不及格' end '语文' from score;

总结
