MySQL 常用内置函数
- 数学函数
- 字符串函数
- 日期函数
- 条件函数
- 加密函数
数学函数
abs(n)
: 求一个数字的绝对值sqrt(n)
: 求一个数字的 正的算术平方根mod(n, m)
: 求n/m
的 余数ceil(n)
: 对一个数字 向上 取整3.1 ----> 4
floor(n)
: 向下取整round(n)
: 四舍五入取整round(n, p)
: 四舍五入 保留p
位小数rand()
: 返回一个 0-1 的随机数,包含0
和1
truncate(n, p)
: 保留p
位小数pow(x, y)
:x
的y
次幂
字符串函数
char_length(s)
: 获取字符串的长度length(s)
: 获取字符串所占用的字节数lower(s) / lcase(s)
: 将字符串转小写upper(s) / ucase(s)
: 将字符串转大写left(s, len) / right(s, len)
: 左/右截取字符串 指定长度concat(s, s1, ...)
: 拼接字符串concat_ws(sep, s, s1, ...)
: 以sep
作为分隔符,进行字符串的拼接trim(s) , ltrim(s) , rtrim(s)
: 删除空格/左空格/右空格substr(s, start, len)
: 从start
开始截取,截取len
长度 返回子串,start
从1开始substring(s, start, len)
: 和substr
用法相同
日期函数
now()
: 用来获取当前系统时间month(date)
: 获取对应日期的月份year(date)
: 获取对应日期的年份dayofweek(date)
: 返回星期, 星期日 返回1
,…dayofyear(date)
: 获取今天是一年中的第几天datediff(date1, date2)
: 返回两个日期之间相差的天数date_format(date, format)
: 对日期进行格式化处理adddate(date, interval 1 year)
: 增加一年adddate(date, interval 1 month)
: 增加一月adddate(date, interval 1 day)
: 增加一天subdate
: 具体用法和 adddate 相同,代表 减少
format:
%Y : 代表年份
%m : 代表月份
%d : 代表 天
%H : 代表 24进制的小时
%i : 代表 分
%s : 代表 秒
判断函数
if(expr, v1, v2)
:
expr
表达式为true
, 返回v1
, 否则 返回v2
-- 查询 姓名、成绩、及是否及格
select name, score , if(score >=60 ,'及格', '不及格') from t_score ;
ifnull(n, default):
如果n
为null
, 则返回default
,否则返回n
-- 查询所有成绩、没有考试的以 0分 处理
select name , ifnull(score, 0) from t_score ;
case
函数
实现多分支条件判断
case expr when v1 then .. when v2 .. then ..... esle .. end ;
case when expr then ... when expr then ...... else .... end ;
select name , score ,
case
when score >=90 then '良'
when score >=80 then '优'
when score >=70 then '中等'
when score >=60 then '及格'
else '不及格'
end
from t_score ;
case 实现行列转换
select name 姓名 ,
max(case subject when '语文' then score end) 语文,
max(case subject when '数学' then score end) 数学,
max(case subject when '英语' then score end) 英语
from t_score group by name ;
加密函数
md5(str)
: 一般用来实现密码的加密,不可逆的,无法进行解密password(str)
:MySQL
数据库 账号的密码采用的 是password
加密
MySQL数据库给账户设置密码
- 在登录状态下、修改密码
set password = password('新密码');
MySQL
内置的用户 和密码, 在 mysql.user
表存储的