如何使用触发器更新其他表的行?

时间:2015-01-26 09:18:18

标签: mysql triggers

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 |
+---------+-------+-------------+

在上面的设置中,我想计算score_changes中每位用户的得分总和,并将其更新为users.scorescore_changes是动态的,只要用户获得分数就会插入。

  1. 如何在users.score中插入行时自动更新score_changes?触发是最佳选择吗?如何实施?
  2. 使用SUM(SELECT score from score_changes where user_id = users.id);重新计算得分还是仅在users.score中添加新的更改?
  3. 会更好吗?

1 个答案:

答案 0 :(得分:0)

检查此链接是否已使用内部联接。http://dev.mysql.com/doc/refman/5.5/en/update.html 你必须先加入这两个表。您的问题与此相同请参考:MySql update two tables at once