users:
+----+----------+-------------------------------------------+-------------------+-------+
| id | username | password | email | score |
+----+----------+-------------------------------------------+-------------------+-------+
| 1 | user_1 | *79457HG5456756799547645767567E0C18660CF8 | user1@example.com | 0 |
+----+----------+-------------------------------------------+-------------------+-------+
| 2 | user_2 | *79457HG5456756799547645767567E0C18660CF8 | user2@example.com | 0 |
+----+----------+-------------------------------------------+-------------------+-------+
| 3 | user_3 | *79457HG5456756799547645767567E0C18660CF8 | user3@example.com | 0 |
+----+----------+-------------------------------------------+-------------------+-------+
score_changes
+---------+-------+-------------+
| user_id | score | reason |
+---------+-------+-------------+
| 1 | 2 | played well |
+---------+-------+-------------+
| 1 | -2 | foul |
+---------+-------+-------------+
| 2 | -5 | spammed |
+---------+-------+-------------+
| 3 | -10 | cheated |
+---------+-------+-------------+
| 1 | 1 | played well |
+---------+-------+-------------+
In the above setup, I want to calculate the sum of the score of each user in score_changes
and update it to users.score
. score_changes
is dynamic and has inserts whenever a user gains score.
- How do I update
users.score
automatically as and when a row is inserted inscore_changes
? Is trigger the best option? How to implement it? - Is it better to recalculate the score by using
SUM(SELECT score from score_changes where user_id = users.id);
or just add the new change inusers.score
?