MySQL UPDATE 随机数在 1-3 之间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14865632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:34:26  来源:igfitidea点击:

MySQL UPDATE with random number between 1-3

mysqlrandomnumbersbetween

提问by karnival8

Got a big table and I want to add a column that has a randomly chosen number for each record. 1, 2, or 3.

有一个大表,我想为每条记录添加一个随机选择的数字的列。1、2 或 3。

Having a hard time. Any ideas?

过得很艰难。有任何想法吗?

回答by Rabbie

Try this:

尝试这个:

UPDATE tableName SET columnName = FLOOR( 1 + RAND( ) *3 );

From the MySQL documentationfor RAND:

从MySQL文档RAND

Returns a random floating-point value v in the range 0 <= v < 1.0.

返回范围 0 <= v < 1.0 内的随机浮点值 v。

So in the above query, the largest value which could be generated by 1 + RAND()*3would be 3.999999, which when floored would give 3. The smallest value would occur when RAND()returns 0, in which case this would give 1.

所以在上面的查询中,可以生成的最大值1 + RAND()*33.999999,当 floored 时会给出 3。 当RAND()返回 0时会出现最小值,在这种情况下会给出 1。

回答by Faisal

Use RAND()function. It returns a random floating-point value v in the range 0 <= v < 1.0. To obtain a random integer R in the range i <= R < j, use the expression FLOOR(i + RAND() * (j ? i + 1)). For example, to obtain a random integer in the range the range 1<= R < 3, use the following statement:

使用RAND()函数。它返回范围内的随机浮点值 v 0 <= v < 1.0。要获得范围内的随机整数 R i <= R < j,请使用表达式FLOOR(i + RAND() * (j ? i + 1))。例如,要获取 range 范围内的随机整数1<= R < 3,请使用以下语句:

UPDATE tableName
SET ColumnName= FLOOR(1 + rand() * 3);

N.B :RAND()produces random float values from 0 to 1.

注意:RAND()产生从 0 到 1 的随机浮点值。

回答by facuap

Do this

做这个

UPDATE tableName SET columnName = FLOOR(RAND( ) + RAND( ));