-2

I have 2 tables and I need to UPDATE the value of table1 for uid = 0.

Here my tables:

table1: games

id      | uid     | 
--------+---------+
1       | 5       | 
2       | 7       | 
3       | 0       | 

table2: users

idu     | name    | 
--------+---------+
1       | todd    | 
2       | mario   | 
3       | luigi   | 

So basically I need to UPDATE the uid value of the 3rd row of table1 with a random number between 1-3 (idu values of table2).

For the purpose I tried this:

UPDATE games (uid)
SET idu = ORDER BY rand() LIMIT 1 FROM users
WHERE uid = 0;

Why it's not working?

NineCattoRules
  • 2,253
  • 6
  • 39
  • 84

2 Answers2

2

Why can't you do like

UPDATE games SET uid = (
select idu from users ORDER BY rand() LIMIT 1)
WHERE uid = 0;

Per your comment, in that case use a compound condition. So in your case use the ID column as well in condition like

WHERE uid = 0 AND ID = 3;

Which will make sure that only row with ID = 3 getting updated considering the fact that your ID column is primary key / unique key column.

Rahul
  • 76,197
  • 13
  • 71
  • 125
1

I guess this might help you

SELECT @idu := idu FROM users ORDER BY RAND() LIMIT 1;
UPDATE games SET uid = @idu WHERE uid = 0;

However, this will update ALL rows where games.uid = 0 with the same randomly fetched users.idu

Eduardo Escobar
  • 3,301
  • 2
  • 18
  • 15
  • damn :) ...is there any possible solution to avoid it? I need to have diifferent random value for each cell that has 0 value – NineCattoRules Jun 20 '15 at 17:13