Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating table, choosing between 3 random strings - how?

Tags:

mysql

I'm making standard profile pictures for 5000 users, and right now i need to insert a referance in the 'users' table. I don't want all the users to have the same standard profile picture, so i'm trying to update the 'user_profile_image' row with one of the strings listen in the query below.

UPDATE users 
SET user_profile_image = rand('adrian.jpg', 'bendix.jpg', 
hr_skaeg.jpg', `'jeppe.jpg')

The query doesn't seem to work.

Is this way too simple?

Any help is much appreciated!

Kind regards, Mathias

like image 638
Mathias Fyrst Jakobsen Avatar asked May 11 '12 10:05

Mathias Fyrst Jakobsen


2 Answers

RAND() returns a number between 0 and 1; if you multiply it by the number of pictures you have and take the FLOOR(), you can switch on the result with ELT:

UPDATE users SET user_profile_image =
 ELT(1 + FLOOR(RAND()*4), 'adrian.jpg', 'bendix.jpg', 'hr_skaeg.jpg', 'jeppe.jpg');
like image 120
eggyal Avatar answered Nov 16 '22 02:11

eggyal


You need to read the manual. RAND() doesn't do what you seem to think it does.

Try this instead:

UPDATE users
SET user_profile_image = 
    CASE FLOOR(RAND() * 4) 
    WHEN 0 THEN 'adrian.jpg.img' 
    WHEN 1 THEN 'bendix.jpg' 
    WHEN 2 THEN 'hr_skaeg.jpg' 
    WHEN 3 THEN 'jeppe.jpg' 
    END

;

like image 38
Cylindric Avatar answered Nov 16 '22 01:11

Cylindric