我正在尝试在mySQL中设置一个触发器,以便在添加,删除或更新新团队时触发countTeams中的更新,并将基数和countNA等更改为团队的相应国籍。
这是我的表格:
CREATE TABLE countTeams(
base integer PRIMARY KEY,
countNA integer,
countEU integer,
countCN integer,
countSEA integer,
countINT integer,
countCIS integer
);
CREATE TABLE Team(
TeamName varchar (30) PRIMARY KEY,
Captain varchar (30),
Nationality varchar (5) NOT NULL,
CreationDate date,
Description varchar (50),
foreign key(Captain) references Emails(Username)
);
我失败的触发尝试。
CREATE TRIGGER teamsDown
AFTER INSERT ON Team FOR EACH ROW
UPDATE countTeams
BEGIN
SET base = (base - 1)
IF Team.Nationality= "NA" THEN
UPDATE countTeams
SET countNA = (countNA - 1)
ELSEIF Team.Nationality = "EU" THEN
UPDATE countTeams
SET countEU = (countEU - 1)
IF Team.Nationality = "CN" THEN
UPDATE countTeams
SET countCN = (countCN - 1)
IF Team.Nationality = "SEA"
UPDATE countTeams
SET countSEA = (countSEA - 1)
IF Team.Nationality = "INT"
UPDATE countTeams
SET countINT = (countINT - 1)
IF Team.Nationality = "CIS"
UPDATE countTeams
SET countCIS = (countCIS - 1)
END;
答案 0 :(得分:7)
首先,更改您的countTeams表。
CREATE TABLE countTeams(
base int auto_increment PRIMARY KEY,
nationality varchar(5),
how_many int DEFAULT 0
);
然后填写所需的数据。
INSERT INTO countTeams (nationality) VALUES
('NA'),
('EU'),
('CN'),
('SEA'),
('INT'),
('CIS');
现在你必须为insert创建一个触发器,为删除创建一个触发器。更新不会改变任何内容,不确定为什么要为此创建触发器。或者团队的国籍可以随后改变吗?
DELIMITER $$
CREATE TRIGGER inc_countTeams AFTER INSERT ON Team
FOR EACH ROW
BEGIN
UPDATE countTeams SET how_many = how_many + 1 WHERE nationality = NEW.nationality;
END $$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER dec_countTeams AFTER DELETE ON Team
FOR EACH ROW
BEGIN
UPDATE countTeams SET how_many = how_many - 1 WHERE nationality = OLD.nationality;
END $$
DELIMITER ;
修改强>
DELIMITER $$
CREATE TRIGGER dec_countTeams AFTER UPDATE ON Team
FOR EACH ROW
BEGIN
UPDATE countTeams SET how_many = how_many - 1 WHERE nationality = OLD.nationality;
UPDATE countTeams SET how_many = how_many + 1 WHERE nationality = NEW.nationality;
END $$
DELIMITER ;