1

我有一个包含大学数据的数据库。我想创建一个包含 2 个表大学和学生的触发器。

CREATE TABLE IF NOT EXISTS `university` (
`name` varchar(80) COLLATE utf8_bin NOT NULL,
`uni_id` int(11) NOT NULL,
`students` int(11) NOT NULL,
PRIMARY KEY (`uni_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE IF NOT EXISTS `student` (
`firstName` varchar(20) COLLATE utf8_bin NOT NULL,
`lastName` varchar(20) COLLATE utf8_bin NOT NULL,
`student_id` int(11) NOT NULL,
`id_number` varchar(100) COLLATE utf8_bin NOT NULL,
`current_address` varchar(100) COLLATE utf8_bin NOT NULL,
`current_phone` varchar(16) COLLATE utf8_bin NOT NULL,
`date_of_birth` date NOT NULL,
`gender` varchar(100) COLLATE utf8_bin NOT NULL,
`year_of_study` int(11) NOT NULL,
`department_id` int(11) NOT NULL,
`uniId` int(11) NOT NULL,
`study_cycle` varchar(50) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`student_id`,`id_number`),
UNIQUE KEY `student_id` (`student_id`),
UNIQUE KEY `id_number` (`id_number`),
KEY `lastName` (`lastName`),
KEY `uni_id` (`uniId`),
KEY `uniId` (`uniId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

students我希望在tableuniversity中有新条目后触发器增加table student

CREATE TRIGGER s AFTER
INSERT ON student
FOR EACH ROW
BEGIN
UPDATE university SET students=students+1
WHERE uni_id=NEW.uni_id;
END;

当我尝试执行它时,它给了我一个错误。我究竟做错了什么?

4

2 回答 2

1

如果您没有设置另一个分隔符;,则语句将在第一个结束;,您的触发器定义将不完整。你需要告诉MySQL语句应该在你定义的分隔符处结束。之后,您可以使用delimiter ;

delimiter //
CREATE TRIGGER s BEFORE INSERT ON student
FOR EACH ROW
BEGIN
   UPDATE university 
   SET students = students + 1
   WHERE uni_id = NEW.uniid;
END//
delimiter ;

(并尝试将触发器更改为BEFORE

于 2013-07-08T21:40:37.673 回答
0

您应该更改NEW.uni_idNEW.uniId

CREATE TRIGGER s AFTER
INSERT ON student
FOR EACH ROW
  UPDATE university
  SET students=students+1
  WHERE uni_id=NEW.uniId
;

或者您应该重命名student表中的该字段。

小提琴在这里

于 2013-07-08T22:07:51.480 回答