创建MySQL触发器以更新另一个表中的多个记录

时间:2016-01-06 11:10:55

标签: mysql triggers onupdate

我不确定这是否可行。我正在开发一个梦幻高尔夫锦标赛App作为一个项目。用户从六组中挑选出6名高尔夫球手,每组包含十名高尔夫球手。高尔夫球手所在的组由高尔夫球手表中的组布尔值确定。分数表用于记录比赛条目。

我有两张桌子。高尔夫球手表。

            CREATE TABLE golfers (
            golferid INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            firstname VARCHAR(30) NOT NULL,
            secondtname VARCHAR(30) NOT NULL,
            country VARCHAR(50),
            worldranking int(3),
            tournamentposition int(2),
            group1 boolean,
            group2 boolean,
            group3 boolean,
            group4 boolean,
            group5 boolean,
            group6 boolean,
            day1score int(2),
            day2score int(2),
            day3score int(2),
            day4score int(2),
            totalscore int(3),
            golfscoretotal int(3)
            );

还有一张分数表。如下所示。

            CREATE TABLE scores (
            scoreid INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            userid INT(11) NOT NULL,
            golferid1 INT(6),
            golfscoretotal1 INT(3),
            golferid2 INT(6),
            golfscoretotal2 INT(3),
            golferid3 INT(6),
            golfscoretotal3 INT(3),
            golferid4 INT(6),
            golfscoretotal4 INT(3),
            golferid5 INT(6),
            golfscoretotal5 INT(3),
            golferid6 INT(6),
            golfscoretotal6 INT(3),
            totalscore INT(4),
            FOREIGN KEY fk_userid REFERENCES users(id) 
            );

是否可以根据golfscoretotal1栏前golofid1 INT(6)栏中高尔夫球手的id更新每个高尔夫球手的得分表(取自高尔夫球手表)中的得分。

1 个答案:

答案 0 :(得分:-1)

你可以使用像golverid1这样简单的东西:

CREATE TRIGGER update_scores1 After INSERT ON golfers FOR EACH ROW 
       UPDATE scores
       SET golfscoretotal1 = new.golfscoretotal
       WHERE golferid1 = NEW.golferid

然后对于其他人来说,只需创建更多这样的触发器,总共产生6个触发器:

CREATE TRIGGER update_scores2 After INSERT ON golfers FOR EACH ROW 
       UPDATE scores
       SET golfscoretotal2 = new.golfscoretotal
       WHERE golferid2 = NEW.golferid