I have an users table where I store user info along with a reputation score like Stackoverflow has.
My question is how to update multiple users’ reputations with a single MySQL query.
Here’s my users table
user_id reputation
1 11
2 202
3 3003
4 444
5 555
Let’s say user_id=1 downvotes user_id=4 and user_id=5. In this scenario user_id=1’s reputation loses 2 points and user_id=4,5 both lose 10 points.
The users table would then look like this:
user_id reputation
1 9 //lost 2 points
2 202
3 3003
4 434 //lost 10 points
5 545 //lost 10 points
I know the MySQL query shown below works but I’m wondering a generalizable solution in the case that the number of users to UPDATE is variable and depends on the voting.
UPDATE `users`
SET `reputation` = CASE
WHEN `user_id` = '1' THEN reputation - 2
WHEN `user_id` = '4' THEN reputation - 10
WHEN `user_id` = '5' THEN reputation - 10
ELSE `reputation` END
You can replace the second
WHENwith anIN()clause. It still requires some dynamic query building in your application code, but if your API allows direct binding of arrays into anIN()clause, this is much easier.I will admit I find it a bit awkward to force all of this into one query though. Unless performance is a real issue, I would rather see this as two queries wrapped in a transaction – one to subtract
-2fromuser_id=1and one to subtract the-10users.Documentation on MySQL transaction handling…