tags:

views:

1415

answers:

2

Hi

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.

+11  A: 
SET @r := 0;
UPDATE  items2
SET     author_id = (@r := @r + 1)
ORDER BY
        RAND()
Quassnoi
Can you really order by rand? That seems weird to me, because doesn't that mean it would have to call "rand" on a row every time it compared it to another row?
Paul Tomblin
It first selects RAND()s as temporary values along with normal records, then sorts on these temporary values. It's same as SELECT * FROM (SELECT id, RAND() AS rnd FROM table) ORDER BY rnd
Quassnoi
cool! +1 for "zen-ness"
Jason S
Woah! Great answer!
ceejayoz
A: 
SET @i=1;
SELECT t.*, @i as RAND_NUM, @i:=@i+1 FROM your_table t ORDER BY RAND();
vartec