For this (pseudo code) example I have two tables in MySQL:
member { id, name }
names { name }
There are 100 members in member and 10 names. I want to use a random name from names to update the member table. So far I’ve got this, but, not sure if there is a better method to achieve it.
UPDATE member SET name = (SELECT name FROM names ORDER BY RAND() LIMIT 1);
The code will be executed from a script so I’m looking to avoid functions etc.
Thanks in advance.
You could avoid ordering by rand() by adding id column to your names table and using:
With only 10 names the result won’t be much faster, but you would see the difference if you wanted to choose from a bigger set of names as sorting by rand() starts being inefficient quite fast and you do it for every row in members.
Update:
Seems like rand() inside where gives unpredictable results.
Use this one instead:
Number of rows affected may vary, if random name matches the one already in the table it doesnt count as update.