Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL insert random from list

Tags:

random

mysql

I would like to add a random value to a table. While I know how to add random integers within a range, I am currently stumped on how to add a randomly selected item from a list.

Let's say I have a MYSQL table for IM accounts. I would like to fill it with random data.

INSERT INTO `im` (`im`, `service`) SELECT LOWER(`last`), RANDOM-SELECTION-HERE FROM `contact`; 

What this query should do is add to the IM table the contact's last name with a random selection from an array I would give. For example, the array would be:

['AIM', 'ICQ', 'MSN', 'Yahoo', 'GTalk', 'Other'] 

So, I would like to add the users last name plus one of the random items from the array.

NOTE: I know this is fully possible with a programming language such as PHP, Perl, etc., but I am not trying to do that. Please try to provide a way to do this strictly with MYSQL.

like image 200
Ali Karbassi Avatar asked Aug 19 '09 18:08

Ali Karbassi


People also ask

How can we get a random number between 1 and 100 in MySQL?

select FLOOR( RAND() * (maximumValue-minimumValue) + minimumValue) as anyVariableName; Let us check with some maximum and minimum value. The maximum value we are considering is 200 and minimum is 100. The random number will be between 100 and 200 including 100 and 200 itself.

How do I fill a column with random numbers in MySQL?

UPDATE yourTableName set yourColumnName=value where yourColumnName2=(SELECT FLOOR(1+RAND()*3)); In the above query, the statement FLOOR(1+RAND()*3) generates the number between 1-3 and update the column.


1 Answers

INSERT INTO `im` (`im`, `service`) SELECT LOWER(`last`),     ELT(0.5 + RAND() * 6, 'AIM', 'ICQ', 'MSN', 'Yahoo', 'GTalk', 'Other') FROM `contact` 
like image 110
chaos Avatar answered Sep 20 '22 20:09

chaos