我一直在尝试根据数据插入表格中的表格中设置自动增量,
因为这被标记为重复,我已经查看了其他问题,我认为我的主要问题是误解了触发器的语法,特别是行:
WHERE ID = NEW.ID;
MySQL Block:
CREATE TABLE Members(
ID INT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE,
FIRST_NAME TEXT(16),
LAST_NAME TEXT(16),
TITLE TEXT(7), /** 7 CHARS for 'Student'*/
INSTITUTION VARCHAR(2048),
No_Publications INT NOT NULL,
PRIMARY KEY(ID)
);
CREATE TABLE Papers(
ISBN INT UNSIGNED NOT NULL UNIQUE,
Title TEXT(4),
Publish_Date DATE NOT NULL,
Topic TEXT(128),
PRIMARY KEY(ISBN)
);
CREATE TABLE Publications(
Researcher_ID INT UNSIGNED NOT NULL UNIQUE,
ISBN INT UNSIGNED NOT NULL UNIQUE,
PRIMARY KEY (Researcher_ID, ISBN),
FOREIGN KEY(Researcher_ID) REFERENCES Members(ID) ON DELETE RESTRICT ON UPDATE CASCADE,
FOREIGN KEY(ISBN) REFERENCES Papers(ISBN) ON DELETE RESTRICT ON UPDATE CASCADE /**Used in
many to many relations*/
);
CREATE TRIGGER New_Publication AFTER INSERT ON Publications
FOR EACH ROW
BEGIN
UPDATE Members SET No_Publications = No_Publications + 1 WHERE ID = NEW.ID;
END;
编辑: 插入Publications表后,我希望Members表中的No_Publication列增加一个
答案 0 :(得分:0)
id
表格中没有publications
字段,因此不能有任何NEW.ID
。你必须在mysql中收到一个未知的字段错误。 publications
的create table语句包含有关在更新中使用哪个字段的线索:
FOREIGN KEY(Researcher_ID) REFERENCES Members(ID)
因此,更新应如下所示:
UPDATE Members SET No_Publications = No_Publications + 1 WHERE ID = NEW.Researcher_ID
此外,不需要begin ... end
,因为触发器主体包含一个sql语句:
CREATE TRIGGER New_Publication AFTER INSERT ON Publications
FOR EACH ROW
UPDATE Members SET No_Publications = No_Publications + 1 WHERE ID = NEW.Researcher_ID;