How can I increment a column by one in a trigger?

主宰稳场 提交于 2021-02-07 20:28:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!