mysql触发其他表中的递增/递减值

8ftvxx2r  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(416)

我有两个独立的表格记录着联盟中的球队和球队的比赛。我在表'team'中有一个字段,用于每个团队的获胜情况,我正在尝试在mysql中创建一个触发器,以便在插入/更新获胜团队的游戏时自动更新此字段,反之,在更新/删除游戏时将其递减。这些是我的table:

CREATE TABLE team (
teamName varchar(32) NOT NULL,
teamManager varchar(32) NOT NULL,
teamPoints decimal(6,2) DEFAULT 0,
teamWins tinyint(255) unsigned DEFAULT 0,
leagueID tinyint(255) unsigned NOT NULL,
FOREIGN KEY (leagueID) REFERENCES league (leagueID),
PRIMARY KEY (teamName, leagueID));

CREATE TABLE game (
gameID int NOT NULL AUTO_INCREMENT,
gameDate date NOT NULL,
winningTeam varchar(32) NOT NULL,
losingTeam varchar(32) DEFAULT NULL,
leagueID tinyint(255) unsigned NOT NULL,
FOREIGN KEY (leagueID) REFERENCES league (leagueID),
FOREIGN KEY (winningTeam) REFERENCES team (teamName),
FOREIGN KEY (losingTeam) REFERENCES team (teamName),
PRIMARY KEY (gameID));

以及我试图添加的触发器:

CREATE TRIGGER addWin
AFTER INSERT, UPDATE ON game
AS
BEGIN
    UPDATE team
    SET team.teamWins = team.teamWins + 1
    WHERE team.teamName IN (SELECT inserted.winningTeam FROM inserted)
END;
mwg9r5ms

mwg9r5ms1#

您的触发器看起来像sql server触发器。在mysql中,这看起来更像:

DELIMITER $$

CREATE TRIGGER addWin AFTER INSERT ON game
AS
BEGIN
    UPDATE team
        SET teamWins = teamWins + 1
        WHERE teamName = new.winningTeam;
END;$$

DELIMITER ;

更新触发器会更复杂,因为您必须撤消上一个增量。我把这个留给你。

相关问题