在 MYSQL 中将随机数插入表中 [英] Inserting random numbers into a table in MYSQL

查看:31
本文介绍了在 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

这篇关于在 MYSQL 中将随机数插入表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆