如果在mysql触发器中阻塞,则使用Case语句

时间:2018-05-12 23:51:54

标签: mysql triggers

我是mysql触发器的新手。 假设我有一个表名教师包含

teacher_id,
teacher_name,
description,
student_id,
class,
student_year 

我想在教师表上创建一个AFTER INSERT和AFTER UPDATE触发器。 为此,我有一个名为 teacherslogs 的表名,包含id,teacher_id,student_year,class,student_id列

因此,只要记录插入教师表,就应插入教师日志。(此触发器能够写入)

但是面对问题后更新触发器。

要求

每当 student_id 教师表中更改时,我们需要在教师日志中插入记录,并在教师表格中为该记录添加其他列更改  为此,我写得像这样

  IF ((NEW.student_id <=> OLD.student_id) = 0) Then
    select student_id,class,student_year into student_id_,class_,year_ from `employees`.`teachers` where teacher_id = OLD.teacher_id;
    Insert into `employees`.`teacherlogs`(teacher_id,student_year,class,student_id) values (OLD.teacher_id,year_,class_,student_id_);
    END IF;

但是每当其他列(如class,student_year)发生更改时,我们都需要更新该记录的 teacherslogs 表,其中teacher_id和student_id

最终触发查询

create trigger `updateteacherlogs`
AFTER UPDATE ON `employees`.`teacher` FOR EACH ROW 
BEGIN
    DECLARE teacher_id_ int(11);
    Declare student_id_ int(11);
    Declare class_ varchar(150);
    Declare year_ int(11);
    Declare dummy tinyint;

    IF ((NEW.student_id <=> OLD.student_id) = 0) Then
    select student_id,class,student_year into student_id_,class_,year_ from `employees`.`teachers` where teacher_id = OLD.teacher_id;
    Insert into `employees`.`teacherlogs`(teacher_id,student_year,class,student_id) values (OLD.teacher_id,year_,class_,student_id_);
    ELSE
         CASE WHEN (NEW.student_year <=> OLD.student_year) = 0
         THEN update `teacherlogs` set student_year = NEW.student_year where student_id=OLD.student_id and teacher_id = OLD.teacher_id;
         WHEN (NEW.class <=> OLD.class) = 0
         THEN update `teacherlogs` set class = NEW.class where student_id=OLD.student_id and teacher_id = OLD.teacher_id
         ELSE select @dummy  END 

    end if;
END

但是如果我在最后得到例外。

是解决问题的正确方法还是其他任何方式?

1 个答案:

答案 0 :(得分:0)

语法错误的原因是您的CASE语句需要以END CASE;结尾,而不仅仅是END

我不认为CASE声明实际上符合您的要求,但好像NEW.student_year <=> OLD.student_year然后NEW.class将无法与OLD.class进行比较,看看是否该值也需要更新。那是因为(来自manual):

  

对于第二种语法,每个WHEN子句的search_condition表达式都是   评估直到一个为真,此时它对应的那个   子句statement_list执行

您只需将ELSE CASE ...替换为ELSEIF子句即可解决这个问题:

ELSEIF NEW.student_year <=> OLD.student_year OR NEW.class <=> OLD.class THEN
UPDATE teacherlogs
  SET student_year = NEW.student_year, class = NEW.class 
  WHERE student_id = OLD.student_id AND teacher_id = OLD.teacher_id;

这应该有效,因为(基于我对您的数据库配置方式的理解),student_yearclassteacherlogs的值应与{{1}相同}和OLD.student_year如果它们与OLD.classNEW.student_year相同,则值不会更新。

如果我的理解不正确,您需要修改更新以对每个值有条件:

NEW.class