MySQL函数

1. 字符串函数

1.1 常用字符串函数
函数功能
concat(S1,S2,...Sn)字符串拼接,将S1,S2,... Sn拼接成一个字符串
lower(str)将字符串str全部转为小写
upper(str)将字符串str全部转为大写
lpad(str,n,pad)左填充,用字符串pad对str的左边进行填充,达到n个字符串长度
rlap(str,n,pad)右填充,用字符串pad对str的右边进行填充,达到n个字符串长度
trim(str)去掉字符串头部和尾部的空格
substring(str,start,len)返回从字符串str从start位置起的len个长度的字符串
1.2 代码演示
-- ---------------------------------------------内置字符串函数
# concat(拼接字符串)
select concat('hello', ' MySQL');

# lower(转小写)
select lower('HELLO');

# upper(转大写)
select upper('hello');

# lpad(左填充)
select lpad('01', 5, '*');

# rpad(右填充)
select rpad('01', 5, '_');

# trim(取出头部和尾部的空格)
select trim('  hello Mysql  ');

# substring(截取)
select substring('hello MySQL', 1, 5);

2. 数值函数

2.1 常用数值函数
函数功能
ceil(x)向上取整
floor(x)向下取整
mod(x,y)返回x/y的模
rand()返回0~1内的随机数
round(x,y)求参数x的四舍五入的值,保留y位小数
2.2 代码演示
-- ---------------------------------------------数值函数
# ceil(向上取整)
select ceil(1.1);

# floor(向下取整)
select floor(1.1);

# mod(求模)
select mod(7,3);

# rand(随机数)
select rand();

# round(保留两位小数,四舍五入)
select round(2.3478979, 2);

# 通过数据库的函数,生成一个6为验证码
select lpad(round(rand() * 1000000, 0), 6, '0');

3. 日期函数

3.1 常用日期函数
函数功能
curdate()返回当前日期
curtime()返回当前时间
now()返回当前日期和时间
year(date)获取指定date的年份
month(date)获取指定date的月份
day(date)获取指定date的日期
date_add(date, interval exprtype)返回一个日期/时间值加上一个时间间隔expr后的时间值
datediff(date1,date2)返回起始时间date1 和 结束时间date2之间的天数
3.2 代码演示
-- ---------------------------------------------日期函数
# curdate(当前年月日)
select curdate();

# curtime(当前时分秒)
select curtime();

# now(当前年月日和时分秒)
select now();

# year(获取当前年)
select year(now());

# month(获取当前月)
select month(now());

# day(获取当前天)
select day(now());

# date_add(当前时间往后推一个时间间隔)
select date_add(now(), interval 100 day);

# datediff(指定时间相差天数)
select datediff('2024-1-1', '2023-5-22');

4. 流程函数

4.1 常用流程函数
函数功能
if(value , t , f)如果value为true,则返回t,否则返回f
ifnull(value1 , value2)如果value1不为空,返回value1,否则返回value2
case when [ val1 ] then [res1] ...else [ default ] end如果val1为true,返回res1,... 否则返回default默认值
case [ expr ] when [ val1 ] then [res1] ... else [ default ] end

如果expr的值等于val1,返回res1,... 否则返回default默认值

4.2 代码演示
-- ---------------------------------------------流程函数
# if(条件为真返回OK,否则error)
select if(true, 'ok', 'error');
select if(false, 'ok', 'error');

# ifnull(判断条件是否为空)
select ifnull('ok', 'default');
select ifnull('', 'default');
select ifnull(NULL, 'default');

# case when then else end
-- 需求:查询emp表的员工姓名和工作地址
select
    name,
    (case workaddress when '蜀国' then '帝为备也!' when '吴国' then '帝为权也!'else '帝为操也!'end) as '工作地址'
from emp;
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值