问题
I need help writing a MySQL trigger.
Suppose you have a student database with the following tables:
ENROLLMENT(SSN, CLASS_NO, GRADE)
CLASS(CLASS_NO, CLASS_TITLE, NO_OF_STUDENTS).
I need to write a trigger to increase the NO_OF_STUDENTS
by one if a new student is added to the ENROLLMENT
table for that CLASS_NO
.
回答1:
you can use mysql trigger to do this. Try something like
CREATE TRIGGER 'database_name'.'after_insert_enrollment' AFTER INSERT ON 'ENROLLMENT'
FOR EACH ROW
BEGIN
UPDATE class SET NO_OF_STUDENTS = NO_OF_STUDENTS +1 WHERE CLASS_NO = NEW.CLASS_NO;
END
回答2:
I'd also decrease no_of_studens
in case an enrollment is deleted.
delimiter //
CREATE TRIGGER AFTER_INS_ENROLLMENT AFTER INSERT ON ENROLLMENT
FOR EACH ROW
BEGIN
UPDATE CLASS SET NO_OF_STUDENTS = NO_OF_STUDENTS + 1 WHERE CLASS_NO = NEW.CLASS_NO;
END;//
delimiter;
delimiter //
CREATE TRIGGER AFTER_INS_ENROLLMENT AFTER DELETE ON ENROLLMENT
FOR EACH ROW
BEGIN
UPDATE CLASS SET NO_OF_STUDENTS = NO_OF_STUDENTS - 1 WHERE CLASS_NO = NEW.CLASS_NO;
END;//
delimiter ;
回答3:
why would you store this in a record? Perhaps you should use Select COUNT(Student_Id) from Students Where Class_Id = @Class_Id
回答4:
Have you tried something like:
delimiter |
CREATE TRIGGER testref BEFORE INSERT ON ENROLLMENT
FOR EACH ROW BEGIN
UPDATE CLASS SET NO_OF_STUDENTS = NO_OF_STUDENTS + 1 WHERE CLASS_NO = NEW.CLASS_NO;
END;
|
delimiter ;
来源:https://stackoverflow.com/questions/8474575/how-can-i-increment-a-column-by-one-in-a-trigger