0

我正在努力实现以下目标:

当我添加到 Player_goals 表中时, player_John在match_xx中获得了 3 player_goals - 它不仅被插入到Players_goals表中,而且还被插入到Players 表中。如果 player_John 已经进了 2 个球,它会更新为 5(总和)。

请参阅下面我使用的表格:

Players table
+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| player_id    | int(4)      | NO   | PRI | NULL    | auto_increment |
| player_name  | varchar(45) | NO   | MUL | NULL    |                |
| team_name    | varchar(45) | NO   | MUL | NULL    |                |
| player_goals | int(4)      | YES  |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+

Players_goals table
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| player_name | varchar(45) | NO   | MUL | NULL    |       |
| match_id    | int(4)      | NO   | MUL | NULL    |       |
| goals       | int(4)      | YES  | MUL | NULL    |       |
+-------------+-------------+------+-----+---------+-------+

我怎样才能做到这一点?

4

3 回答 3

0

下面只是用于理解逻辑的虚拟代码,你可以通过这个

CREATE TRIGGER goalTrigger

AFTER INSERT ( into player_goals  table )

FOR EACH ROW 
BEGIN

INSERT INTO (player table ) VALUES()
ON DUPLICATE KEY UPDATE player_goals = player_goals+current_goles

END

参考

http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html

http://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx

于 2012-04-06T13:18:15.167 回答
0

我会在 Players_goals 的 ONINSERT 事件上设置一个触发器,更新相关的 Players 行

于 2012-04-06T13:18:15.823 回答
0

我假设 Players 表中的 player_goals 是球员在每场比赛中得分的所有目标的总和,直到最近。如果是这样的话:

第一个 player_goals 是您必须避免的冗余数据,您可以通过连接两个表从表 Players_goals 中获取此信息。

第二:如果您必须这样做,您可以使用INSERT语句将此类信息插入到 player_goal 中,并使用UPDATE语句将此类信息插入到 player 表中,在这种情况下,您必须首先从 Players_goals 获取玩家的所有总目标,或者您必须拥有一种增加 Players 表中 player_goals 旧值的方法

于 2012-04-06T13:33:29.443 回答