MySQL入门-函数
前言
本文是对MySQL中函数部分的总结。
一、函数是什么?
函数是指一段可以直接被另一个程序调用的程序或代码。
二、函数分类
Mysql中函数主要分为以下几类:
- 字符串函数
- 数值函数
- 日期函数
- 流程函数
下面分别对这几类函数进行介绍。
1.字符串函数
常见的字符串函数如下表所示
使用示例:
-- 1.字符串函数
-- concat
select concat('hello','mysql'); -- hellomysql
-- lower
select lower('HELLO'); -- hello
-- upper
select upper('hello'); -- HELLO
-- lpad
select lpad('01',5,'0'); -- 00001 以后面的字符将前面的拼接成5位,在左侧添加
-- rpad
select rpad('01',5,'0'); -- 01000 以后面的字符将前面的拼接成5位,在右侧添加
-- trim
select trim(' hello mysql '); -- hello mysql 删除两侧空格
-- substring 索引从1开始
select substring('hello',1,3); -- hel
2.数值函数
常见的数值函数如下表所示
使用示例
-- ceil
select ceil(1.5); -- 2
-- floor
select floor(1.9); -- 1
-- mod
select mod(3,4); -- 3
-- rand
select rand();
-- round 保留两位小数
select round(2.34,2); -- 2.34
select round(2.345,2); -- 2.35
案例:生成六位随机验证码
select lpad(round(rand()*1000000,0),6,'0');
select rpad(round(rand()*1000000,0),6,'0');
3.日期函数
常见的日期函数如下表所示
使用示例
-- 日期函数
-- curdate()
select curdate(); -- 2022-07-08
-- curtime()
select CURTIME(); -- 22:55:21
-- now
select NOW(); -- 2022-07-08 22:55:38
-- Year
select year(now()); -- 2022
-- month
select month(now()); -- 7
-- day
select day(now()); --8
-- date_add
select date_add(now(),INTERVAL 70 YEAR); -- 2092-07-08 22:56:36
-- datediff
select datediff('2023-12-15','2022-12-15'); -- 365
案例:查询所有员工入职天数,并根据入职天数倒序排序
select name,datediff(curdate(),entrydate) as 'entrydays' from emp order by entrydays desc;
4.流程函数
常见的流程函数如下表所示
使用示例
-- if
select if(true,'ok','Error'); --true
-- ifnull
select ifnull('ok','Default'); -- ok
select ifnull(null,'Default'); -- Default
select ifnull('','Default'); -- ''
-- case when then else end
-- 查询emp表的员工姓名和工作地址(北京/上海--一线城市,其他---二线城市)
select
name,
(case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市'end) as '工作地址'
from emp;
总结
本篇文章对MySQL中的函数进行了介绍,主要包括字符串函数、数值函数、日期函数、流程函数。希望大家能够共同学习,文中有错误麻烦请指出,不胜感激。