MySQL自娱—5.常用函数
函数类似于java的方法,将一组逻辑语句封装在方法体中,对外暴露方法名
好处是隐藏了实现细节;提高代码的重用性
分类
- 单行函数 如 concat length ifnull等 // 本篇剩余内容全部为单行函数
- 分组函数
字符函数
- length 获取参数值得字节个数,目前来讲只有length是字节长度
- concat 拼接字符串
select concat(a, b) from 表;
- upper, lower 大写,小写
- substr, substring 截取字符串
注意:sql语言中,索引都是从1开始
截取从指定索引处开始所有的字符
第二个数字是长度
select substr(‘xxxxxxxxx’, 1, 3) as out_put;
- instr 返回子串的起始索引
- trim 去前后空格
select trim(x from xyyxx) as out_put; 去字符x
- lpad rpad 左右填充 lpad(xx, 12, yy)
- replace 替换
数学函数
- round 四舍五入
- ceil 向上取整
- floor 向下取整
- truncate 截断
select truncate(1.55555, 1); 小数点后保留几位
- mod 取余
被除数为正,结果为正;被除数为负,结果为负 里边的运算公式是: a-a/b*b
select mod(10, -3)
日期函数
- now 返回当前系统日期+时间 select now();
- curdate 返回当前系统日期, 不包含时间
- curtime 返回当前系统时间, 不包含日期
- 其他写法 year(now())
- monthname 月名 monthname(now())
- str_to_date 将日期格式的字符转换成指定格式的日期
str_to_date('9-3-1999', 'm%-%d-Y%')
- date_format 将日期转换成字符
date_format('2016/6/6, '%Y年%m月%d日')
select date_format(now(), "%y年%m月%d日") as out_put;
其他函数
- select version();
- select database();
- select user();
流程控制函数
- if else 函数
select if(10<5, "大", "小");
select name if(name is null, '没名字', '有名字') 备注 from 表;
- case函数的使用一
- 类似于等于判断
case 要判断的字段或表达式
when 常量1 then 要显示的值1或语句1;(语句加分号)
when 常量2 then 要显示的值2或语句2;
else 要显示的值n或语句n;
end
- select salary 原始工资,department_id,
case department_id
when 30 then salary*1.1
when 40 then salary*1.2
else salary
end as 新工资
from employees;
- case函数的使用二
- 类似于大于小于判断
case
when 条件1 then 要显示的值1或语句1;(语句加分号)
when 条件2 then 要显示的值2或语句2;
。。。
else 要显示的值n或语句n
end
- select salary,
case
when salary > 3000 then "a"
when salary > 2000 then "b"
when salary > 1000 then "c"
else "d"
end as 工资级别
from employees;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!