数值函数
一、MySQL数值函数
序号 |
函数 |
功能 |
1 |
ABS(x) |
返回x的绝对值 |
2 |
CEIL(x) |
返回大于x的最小整数值 |
3 |
FLOOR(x) |
返回小于x的最大整数值 |
4 |
MOD(x,y) |
返回x/y的模 |
5 |
RAND() |
返回0~1内的随机数 |
6 |
ROUND(x,y) |
返回参数x的四舍五入的有y小数位的值 |
7 |
TRUNCATE(x,y) |
返回数值x截断为y小数位的结果 |
1.1 ABS(x)
- 求绝对值:ABS(x)
mysql> select ABS(-0.5),abs(0.5); +-----------+----------+ | ABS(-0.5) | ABS(0.5) | +-----------+----------+ | 0.5 | 0.5 | +-----------+----------+ 1 row in set (0.00 sec) mysql>
1.2 CEIL(x)
- 返回大于x的最小整数值:CEIL(x)
mysql> select ceil(-0.3),ceil(0.3); +------------+-----------+ | ceil(-0.3) | ceil(0.3) | +------------+-----------+ | 0 | 1 | +------------+-----------+ 1 row in set (0.00 sec) mysql>
1.3 FLOOR(x)
- 返回小于x的最大整数值:FLOOR(x)
mysql> select floor(-0.3),floor(0.3); +-------------+------------+ | floor(-0.3) | floor(0.3) | +-------------+------------+ | -1 | 0 | +-------------+------------+ 1 row in set (0.00 sec) mysql>
1.4 MOD(x,y)
- 返回x/y的模:MOD(x,y)
注意:模数和被模数任何一个为null,结果都是null
mysql> select mod(1,2),mod(2,1),mod(null,3),mod(3,null); +----------+----------+-------------+-------------+ | mod(1,2) | mod(2,1) | mod(null,3) | mod(3,null) | +----------+----------+-------------+-------------+ | 1 | 0 | NULL | NULL | +----------+----------+-------------+-------------+ 1 row in set (0.00 sec) mysql>
1.5 RAND()
- 返回0~1内的随机数:RAND()
注意:每次执行结果都不一样
mysql> select rand(),rand(); +--------------------+--------------------+ | rand() | rand() | +--------------------+--------------------+ | 0.6283992907296859 | 0.5261678123159035 | +--------------------+--------------------+ 1 row in set (0.00 sec) mysql>
1.6 ROUND(x,y)
- 返回参数x的四舍五入的有y小数位的值:ROUND(x,y)
注意,如果不写y,默认y为0
mysql> select round(0.12345,3),round(0.12345,4),round(0.12345); +------------------+------------------+----------------+ | round(0.12345,3) | round(0.12345,4) | round(0.12345) | +------------------+------------------+----------------+ | 0.123 | 0.1235 | 0 | +------------------+------------------+----------------+ 1 row in set (0.00 sec) mysql>
1.7 TRUNCATE(x,y)
- 返回数值x截断为y小数位的结果:TRUNCATE(x,y)
注意;仅仅是截断,而不是四舍五入
mysql> select truncate(0.12345,3),truncate(0.12345,4); +---------------------+---------------------+ | truncate(0.12345,3) | truncate(0.12345,4) | +---------------------+---------------------+ | 0.123 | 0.1234 | +---------------------+---------------------+ 1 row in set (0.00 sec) mysql>