为什么这个触发器不按我想要的方式工作?

时间:2011-05-17 01:15:01

标签: mysql triggers

我的mysql数据库中有两个表: 顾问:身份证 学生:顾问ID |主要

我想更新学生,其中Advisor中已删除的ID等于advisorID,并使用一组if语句根据该学生的专业更改该学生的advisorID值。这就是我到目前为止所做的:

    delimiter //
    create trigger advisor_delete after delete
    on advisor
        UPDATE Student
            IF Student.major = 'major1' THEN SET Student.advisorID = 1;
            ELSEIF Student.major = 'major2' THEN SET Student.advisorID = 2;
            ELSEIF Student.major = 'major3' THEN SET Student.advisorID = 3;
            ELSE SET Student.advisorID = 4;
            ENDIF;
        WHERE Student.advisorID = OLD.id;
    end//

欢迎任何帮助。感谢。

1 个答案:

答案 0 :(得分:1)

我不知道这种UPDATE/IF ELSEIF语法,但CASE语句适合您:

delimiter //
create trigger advisor_delete after delete
on advisor
    UPDATE Student
        SET Student.advisorID = 
            CASE Student.major WHEN 'major1' THEN 1
                               WHEN 'major2' THEN 2
                               WHEN 'major3' THEN 3
                               ELSE 4
            END
    WHERE Student.advisorID = OLD.id;
end//