在MySQL下有不少可以直接调用的函数,下面就来进行讲解:
目录
[4.1 user](#4.1 user)
[4.2 md5](#4.2 md5)
[4.3 password](#4.3 password)
[4.4 ifnull](#4.4 ifnull)
[4.5 find_in_set](#4.5 find_in_set)
一、日期函数
函数名称 | 描述 |
---|---|
current_date() | 当前日期 |
current_time() | 当前时间 |
current_timestamp () | 当前时间戳 |
date(datetime) | 返回datetime参数的日期部分 |
date_add(date,interval d_value_type) | 在date中添加日期或时间 interval后的数值单位可以是:year/month/day/hour/minute/second |
date_sub(date,interval d_value_type) | 在date中减去日期或时间 interval后的数值单位可以是:year/month/day/hour/minute/second |
datediff(date1, date2) | 两个日期的差,单位是天 |
now() | 当前日期时间 |
下面是各类函数的演示:
(1)获取各类时间:

(2)使用date截取日期部分:

(3)在日期的基础上使用date_add加日期:

(3)在日期的基础上使用date_sub减去时间:

(4)使用datediff计算两个日期之间相差多少天:

二、字符串函数
函数名称 | 描述 |
---|---|
charset(str) | 返回字符串的编码格式 |
concat(string [,...]) | 连接字符串 |
instr(string,substring) | 返回substring在string中出现的位置,没有返回0 |
ucase(string) | 转换成大写 |
lcase(string) | 转换成小写 |
left(string, length) | 从string中的左边起取length个字符 |
right(string, length) | 从string中的右边起取length个字符 |
length(string) | string的总字节数 |
replace(str, search_str,replace_str) | 在str中用replace_str替换search_str |
strcmp(stringl, string2) | 逐字符比较两字符串大小 |
substring(str, position [,length]) | 从str的postion开始,向右取length个字符 |
ltrim(string) | 去除string前空格 |
rtrim(string) | 去除string后空格 |
trim(string) | 去除string前空格和后空格 |
下面是各类函数的演示:
(1)使用charset获取字符串的编码格式

(2)使用concat连接字符串

我们看到该函数即便传入数字也可以将其转换为字符串形式
(3)使用instr查找子串出现位置

(4)使用ucase、lcase分别将字符串转化为大小写

(5)使用left和right分别从字符串的左边或右边开始提取字符


(6)使用length来求字符串总字节数

但是在这里要注意一下:在utf8下是变长编码,所以英文字母和数字一个只占1字节,中文字符一个占3个字节
(7)使用replace来替换符

(8)使用substring来截取字符串

使用时可以忽略传入的length的值,即从postion位置截取到字符尾部
(9)使用trim/ltrim/rtrim来去除字符串中前后/前/后空格

我们可以看到该函数不会去除字符串中间的空格符
三、数学函数
函数名称 | 描述 |
---|---|
abs(number) | 绝对值函数 |
bin(decimal_number) | 十进制转换二进制(只保留整数部分) |
hex(decimal_Number) | 十进制转换成十六进制(只保留整数部分) |
conv(number,from_base,to_base) | 将number从from_base进制转换为to_base进制(只保留整数部分) |
ceiling(number) | 向右取整 |
floor(number) | 地板取整 |
format(number, decimal_places) | 格式化,保留decimal_places位小数 |
rand() | 返回随机浮点数,范围[0.0,1.0),小位数最多为17位 |
mod(number,denominator) | 取模,求余 |
下面是一些函数的演示:
(1)进制转换

(2)使用format格式化小数
(3)使用mod进行模运算

关于取模的运算规则可以看这篇文章:
(4)使用rand函数来生成随机数
直接生成小数:

套用函数生成想要范围内整数:

(5)使用ceiling/floor对小数进行取整

四、其他函数
4.1 user
我们可以调用user函数来查看当前使用MySQL的用户身份:

4.2 md5
该函数会对输入任意长度的消息进行运行,产生一个128位的消息摘要(32位的数字字母混合码),属Hash算法一类,它具有不可逆和低碰撞的特性,特别在用户密码保存方面得到广泛应用。
例如:
我们向该表插入数据:

可以看到直接插入密码数据在查询数据时可以直接看到,如果信息泄露将是十分危险的
这时我们插入密码数据时就可以选择用md5函数来加密一下:

当我们要比对被md5函数修饰过后的数据时,要将比对数据也进行md5函数的修饰:

4.3 password
除了md5,MySQL还提供了一种算法更复杂的函数来加密密码:password

4.4 ifnull
ifnull(val1, val2)如果val1为null,返回val2,否则返回val1的值:

4.5 find_in_set
find_in_set(sub,str_list) :如果 sub 在 str_list 中,则返回下标;如果不在,返回0; str_list 用逗号分隔的字符串。

但是该函数只能查一个元素是否在集合内,如果我们传入多个元素就不起作用了:

该函数经常用来对set类型的查找,下面我们有一张这样的表:

现在我们要找出hobby中有篮球的用户:

可以看到我们之间使用=来查找只能找到hobby只有篮球的用户
这时就轮到find_in_set函数上场了:

本期博客到这里就结束了,我们下期见~
更多MySQL技能请看:http://t.csdn.cn/W9dQl
博主努力更新中~