MySQL常用函数大锦囊

1.字符串函数

函数 功能
concat(s1, s2,…,sn) 链接s1,s2,…,sn为一个字符串
insert(str, x, y, instr) 将字符串str从x位置开始,y个字符长度的子串替换为instr字符串
lower(str) 字符串中所有字符变小写
upper(str) 字符串所有字符变大写
left(str, x) 返回str字符串最左边的x个字符
right(str, x) 返回最右边x个字符
lpad(str, n, pad) 用字符串pad对str最左边进行填充, 直到长度为n个字符长度
rpad(str, n, pad) 用字符串pad对str最右边进行填充, 直到长度为n个字符长度
ltrim(str) 去掉字符串str左侧的空格
rtrim(str) 去掉字符串str右侧的空格
repeat(str, x) 返回str重复x次的结果
replace(str, a, b) 用字符串b去替换str中出现的所有a
strcmp(s1, s2) 比较字符串s1, s2
trim(str) 去掉字符串行尾和行头的空格
substring(str, x, y) 返回字符串str x位置起y个长度的字符串

concat
select concat ('aaa', 'bbb', 'ccc'), concat('aaa', null)
结果aaabbbccc, 第二个是NULL
insert
select() insert ('hello world', 7, 5, 'new world')
结果hello new world
lower和upper
select lower('HElLO'), upper(WorlD)
结果hello, WORLD
…其他的用法一样,对照表格就可以

2. 数值函数

函数 功能
abs(x) 绝对值
ceil(x) 返回大于x的最小整数值
floor(x) 返回小于x的最大整数值
mod(x, y) 返回x / y
rand0 返回0-1内的随机值
round(x, y) 返回参数x的四舍五入的有y位小数的值
truncate(x, y) 返回数字x截断为y位小数的值

3.日期和时间函数

函数 功能
curdate() 当前日期
curtime() 返回当前时间
now() 返回当前的日期和时间
unix_timestrap(date) 日期date的Unix时间戳
from_unixtime() 返回Unix时间戳的日期
week(date) 返回日期是一年中的第几周
year(date) 返回日期date的年份
hour(date) 返回date的小时值
minute(data) date的分钟值
monthname(date) 返回date的月份名
date_format(date, fmt) 返回根据fmt规则格式化后的日期
date_add(date, interval expr type) 返回一个日期的时间值加上一个时间间隔后的时间
datediff(expr, expr2) 返回起始时间和结束时间的天数

有关date_format格式化看该图
MySQL常用函数大锦囊
select date_format(now(), '%M, %D, %Y')
MySQL常用函数大锦囊
有关date_add
interval是一个分割关键字,有关后边expr表达式的类型如下:
MySQL常用函数大锦囊
MySQL常用函数大锦囊

4.流程函数

函数 功能
if(value, t, f) 如果value是真,那么返回t,否则就是f
ifnull(value1, value2) 如果value1不为空, 返回value1,否则返回value2
case when [value1] then [result1]… else [default] end 如果value1是真, 返回result1, 否则就是default
case [expr] when [value1] then [result] …else [default] end 如果expr等于value1, 返回result1, 否则返回default

if
MySQL常用函数大锦囊
ifnull
常用这个函数来替代null
select ifnull(name, 'default') from xxx

case when [value1] then [result1]… else [default] end
MySQL常用函数大锦囊
case [expr] when [value1] then [result] …else [default] endMySQL常用函数大锦囊

5.其他常用函数

函数 功能
database() 返回当前数据库名
version() 返回当前数据库版本
user() 返回当前登录用户名
inet_aton(ip) 返回ip地址的数字表示
inet_ntoa(num) 返回数字代表的IP地址
password(str) 返回字符串str的加密版本
MD5() 返回字符串str的MD5值