虽然数据库主要进行的是查询操作,对数据的操作不是很常见,例如前面介绍的日期函数和字符串函数在查询时使用率很高,但是关于数据操作的函数我们还是要了解的。
常见的数学函数如下所示:
1. abs(num)
abs()返回所传入的参数的绝对值,使用如下:
mysql> select abs(-100);
+-----------+
| abs(-100) |
+-----------+
| 100 |
+-----------+
1 row in set (0.01 sec)
2. bin(decimal_num)/hex(decimal_num)
bin()函数将传入的十进制数字返回其二进制的值,同理,hex()是将十进制数返回为十六进制的值,使用如下:
mysql> select bin(100);
+----------+
| bin(100) |
+----------+
| 1100100 |
+----------+
1 row in set (0.02 sec)
mysql> select hex(10);
+---------+
| hex(10) |
+---------+
| A |
+---------+
1 row in set (0.00 sec)
3. ceiling(number)/floor(number)
(num)是将num向上取整,floor(num)是将num向下取整,这里要注意的是向上向下和四舍五入不一样。以ceiling为例,如果num是1.1,四舍五入得到的结果是1,但是向上取整的结果是2,使用如下:
mysql> select ceiling(1.1);
+--------------+
| ceiling(1.1) |
+--------------+
| 2 |
+--------------+
1 row in set (0.02 sec)
mysql> select floor(1.9);
+------------+
| floor(1.9) |
+------------+
| 1 |
+------------+
1 row in set (0.00 sec)
-- 对负数向上取整
mysql> select ceiling(-1.9);
+---------------+
| ceiling(-1.9) |
+---------------+
| -1 |
+---------------+
1 row in set (0.00 sec)
特别注意负数向上向下取整的情况。
4. conv(num, from_base, to_base)
conv()的功能是转换数字的进制,from_base是num本身的进制,to_base是希望转换成的进制,使用如下:
-- 将十进制的数字10转换为二进制
mysql> select conv(10, 10, 2);
+-----------------+
| conv(10, 10, 2) |
+-----------------+
| 1010 |
+-----------------+
1 row in set (0.00 sec)
-- 使用bin验证结果
mysql> select bin(10);
+---------+
| bin(10) |
+---------+
| 1010 |
+---------+
1 row in set (0.00 sec)
5. format(num, decimal_place)
format()函数在java的String类也有提供,作用是得到指定保留小数位数的数,使用如下:
mysql> select format(11.123456, 2);
+----------------------+
| format(11.123456, 2) |
+----------------------+
| 11.12 |
+----------------------+
1 row in set (0.02 sec)
6. rand()
rand()函数返回一个0~1的随机值,类型是double型的浮点数,一般使用它得到一个指定范围的随机数,使用方法如下:
-- 得到一个0~100范围内的随机数
mysql> select format(rand()*100, 0);
+-----------------------+
| format(rand()*100, 0) |
+-----------------------+
| 93 |
+-----------------------+
1 row in set (0.00 sec)