mysql rand函数

本文深入探讨了MySQL rand()函数的工作原理,包括如何生成0到1之间的随机浮点数,以及指定种子值时如何产生固定序列的值。同时,文章提醒读者避免在查询中使用rand()函数,因为它可能导致性能问题,并且在基于语句的复制中使用rand()函数可能引起警告。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Returns a random floating-point valuevin the range0<=v<1.0. If a constant integer argumentNis specified, it is used as the seed value, which produces a repeatable sequence of column values.

若未指定参数,那么返回的值为0到1之间的浮点数;若指定了随机因子那么产生的值是固定的。

测试样例如下:

mysql> select rand(),rand(5);
+-------------------+-------------------+
| rand() | rand(5) |
+-------------------+-------------------+
| 0.406958082138522 | 0.406135974830143 |
+-------------------+-------------------+
1 row in set (0.00 sec)

mysql> select rand(),rand(5);
+------------------+-------------------+
| rand() | rand(5) |
+------------------+-------------------+
| 0.16665149123096 | 0.406135974830143 |
+------------------+-------------------+
1 row in set (0.00 sec)

mysql> select rand(),rand(5);
+-------------------+-------------------+
| rand() | rand(5) |
+-------------------+-------------------+
| 0.612383240472882 | 0.406135974830143 |
+-------------------+-------------------+
1 row in set (0.00 sec)
在官方手册中,还提到如下几点:
1、不要使用rand()在查询中,因为会造成多次扫描。
You cannot use a column withRAND()values in anORDER BYclause, becauseORDER BYwould evaluate the column multiple times.
2、在SBR复制中使用rand()不安全,使用rand()会引起一个警告,官方解释如下:
Beginning with MySQL 5.1.43, this function is flagged as unsafe for statement-based replication; use of this function causes a warning when using statement-based replication, and the statement is logged using the binary format whenbinlog_formatisMIXED. (Bug #49222)

转载于:https://www.cnblogs.com/liufofu/p/4141967.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值