0

I have a database with songs. Every song have an unique id. How I can generate a random unique value for every id in database?

Example:

id | song name    
1  | song1  
2  | song2  
3  | song3

After shuffle

id | song name    
45 | song1  
96 | song2  
10 | song3  

Any idea?

Matt
  • 14,906
  • 27
  • 99
  • 149
Cosmin
  • 478
  • 1
  • 5
  • 16

3 Answers3

1

Use a combination of FLOOR and RAND() to get what you want.

If there are 1000 songs in your db.

SELECT FLOOR(RAND() * (1 - 1000 + 1)) + 1 AS ID, "song name"
FROM yourtable

If there are 7000 songs in your db.

SELECT FLOOR(RAND() * (1 - 7000 + 1)) + 1 AS ID, "song name"
FROM yourtable

Update..

UPDATE yourtable
SET id = FLOOR(RAND() * (1 - 1000 + 1)) + 1;
Matt
  • 14,906
  • 27
  • 99
  • 149
0

Does the ID have to be an integer? If not you could think about using GUIDS . If this is a possibility for you, then you get further information for migrating your table here: Generate GUID in MySQL for existing Data?

Community
  • 1
  • 1
schlonzo
  • 1,409
  • 13
  • 16
0

try this:

SELECT  @nr:=@nr+1 AS nr, tmp.* 
FROM (
  SELECT * FROM yourTable ORDER BY rand()
  ) AS tmp
CROSS JOIN ( SELECT @nr:=0 ) AS parameter
Bernd Buffen
  • 14,525
  • 2
  • 24
  • 39