数值函数:rand、conv、ceiling、floor、abs、sign

47 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 9 天,点击查看活动详情

一、前言

大家好,今天记录的内容是:

  • sign()
  • conv()
  • ceiling()
  • floor()
  • rand()
  • abs()

二、内容

sign

  • sign(x):根据 x 是负、零还是正,返回为-101

比如:

mysql> select sign(123);
+-----------+
| sign(123) |
+-----------+
|         1 |
+-----------+
1 row in set (0.00 sec)

mysql> select sign(-123);
+------------+
| sign(-123) |
+------------+
|         -1 |
+------------+
1 row in set (0.00 sec)

mysql> select sign(0);
+---------+
| sign(0) |
+---------+
|       0 |
+---------+
1 row in set (0.00 sec)

conv

  • conv(n, base1, base2):该函数用于不同进制数之间的转换,
  • 将数字 nbase1 进制数转换为 base2 进制数。

举例:

mysql> select ceiling(2.111);
+----------------+
| ceiling(2.111) |
+----------------+
|              3 |
+----------------+
1 row in set (0.00 sec)

mysql> select ceiling(-2.111);
+-----------------+
| ceiling(-2.111) |
+-----------------+
|              -2 |
+-----------------+
1 row in set (0.00 sec)

备注:

  • 如果有参数为 NULL,则返回 NULL
  • 最小基数为2,最大基数为36
  • 如果 base1 为负数,则 n 被视为有符号数,否则为无符号

ceiling

  • ceiling(x): 返回不小于 X 的最小整数值,也就是向上取整,效果同ceil(x)
  • 如果 X 为 NULL,则返回NULL。

举例:

mysql> select ceiling(2.111);
+----------------+
| ceiling(2.111) |
+----------------+
|              3 |
+----------------+
1 row in set (0.00 sec)

mysql> select ceiling(-2.111);
+-----------------+
| ceiling(-2.111) |
+-----------------+
|              -2 |
+-----------------+
1 row in set (0.00 sec)

floor

  • floor(x): 返回不大于 X 的最大整数值,也就是向下取整。
  • 如果 X 为 NULL,则返回NULL。

举例:

mysql> select floor(2.111);
+--------------+
| floor(2.111) |
+--------------+
|            2 |
+--------------+
1 row in set (0.00 sec)

mysql> select floor(-2.111);
+---------------+
| floor(-2.111) |
+---------------+
|            -3 |
+---------------+
1 row in set (0.00 sec)

rand

  • rand():返回随机数。该随机数值的范围在 0011 之间。

备注:

  • 如果要获得范围在 iijj 之间的随机值,那么表达式应为 :
  • floor(i + rand() * (j − i))
  • 比如获取范围在 111010 之间的随机值,那么可以:
mysql> select floor(1 + rand() * (10 - 1));
+------------------------------+
| floor(1 + rand() * (10 - 1)) |
+------------------------------+
|                            8 |
+------------------------------+
1 row in set (0.00 sec)

abs

abs(x)函数用于返回传入参数的绝对值。

举例:

mysql> select abs(-8);
+---------+
| abs(-8) |
+---------+
|       8 |
+---------+
1 row in set (0.00 sec)

备注:

  • select abs(-9223372036854775808);会报错:
  • BIGINT value is out of range in 'abs(-(9223372036854775808))'
  • 这是因为返回的结果无法存储在带符号的 BIGINT 值中。

三、后话

好了,今天的文章内容就到这里,感谢观看。