在 MYSQL 中将随机数插入表中
我正在尝试计算表中的行数并为随机"字段生成随机数现在这有效:
Im trying to count the number of rows in the table and generate random numbers for the field 'random' Now this works:
SELECT COUNT(*) FROM my_table;
这有效:
UPDATE my_table SET random = FLOOR(6500 * RAND()) + 1;
但这不起作用:
UPDATE my_table SET random = FLOOR((SELECT COUNT(*) ) * RAND()) + 1;
但这会将行数为 0 并加一,因此所有字段都具有数字 1 而不是唯一的随机数.
But this counts the rows as 0 and adds one so all fields have the number one instead of a unique random number.
任何我做错的想法都会最有帮助.
Any ideas what I'm doing wrong would be most helpful.
推荐答案
这个怎么样?
SELECT @cnt := count(*) FROM my_table;
UPDATE my_table SET random = FLOOR(@cnt * RAND()) + 1;
演示:http://sqlfiddle.com/#!2/a896d/4
相关文章