MySQL query to assign a unique random number to each row

大城市里の小女人 提交于 2019-11-27 02:46:09

问题


I wish to attach a column to my table which will be a random number from a sequential list = to the number of rows.

So, if my table had 999 rows, then the numbers 1 to 999 would be assigned randomly and uniquely.

Now, I figured that I could add a dummy TempRandomColumn=Rand(), sort by that and add the numbers sequentially using PHP. But that means 999 MySQL statements.

Is there a way to do this using a single MySQL statement?

Thanks for any pointers.


回答1:


SET @r := 0;
UPDATE  items2
SET     author_id = (@r := @r + 1)
ORDER BY
        RAND()



回答2:


SET @i=1;
SELECT t.*, @i:=@i+1 as RAND_NUM FROM your_table t ORDER BY RAND();


来源:https://stackoverflow.com/questions/602952/mysql-query-to-assign-a-unique-random-number-to-each-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!