MySQL:使用列表中的随机数更新所有行

时间:2014-11-11 17:21:31

标签: mysql sql

我需要运行一个SQL查询,从列表中选择一个随机数并用它更新一个特定的列。

数字列表:

(101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122)

rand table :(结构)

id  rand    type
1    0       false
2    0       true
3    0       false
4    0       true
5    0       true

我需要从列表中选择随机数并更新" rand"柱,

2 个答案:

答案 0 :(得分:7)

如果这些数字不是来自另一张表,但您只想要101到122之间的任意随机数,那么我认为这应该有效:

UPDATE `rand` SET `rand` = FLOOR(RAND() * (22)) + 101

-- or written with the formula below.
UPDATE `rand` SET `rand` = FLOOR(101 + RAND() * (123-101))

来自MySQL文档:

  

获得i <= R <1的范围内的随机整数R. j,使用   表达式FLOOR(i + RAND()*(j - i))。

Sample SQL Fiddle

答案 1 :(得分:6)

试试这个:

UPDATE `rand` SET `rand` = (SELECT val FROM (
    SELECT 101 AS val
    UNION ALL SELECT 102
    UNION ALL SELECT 103
    UNION ALL SELECT 104
    UNION ALL SELECT 105
    UNION ALL SELECT 106
    UNION ALL SELECT 107
    UNION ALL SELECT 108
    UNION ALL SELECT 109
    UNION ALL SELECT 110
    UNION ALL SELECT 111
    UNION ALL SELECT 112
    UNION ALL SELECT 113
    UNION ALL SELECT 114
    UNION ALL SELECT 115
    UNION ALL SELECT 116
    UNION ALL SELECT 118
    UNION ALL SELECT 119
    UNION ALL SELECT 120
    UNION ALL SELECT 121
    UNION ALL SELECT 122
) AS vals ORDER BY RAND() LIMIT 1)

它将在每次执行时使用列表中的随机值更新rand

如果数字列表来自预定义的表格,您可以这样做:

UPDATE `rand` SET `rand` = (SELECT `number` FROM `number_table` ORDER BY RAND() LIMIT 1)