mysql触发器中if else块中的用例语句

t98cgbkg  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(314)

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

teacher_id,
teacher_name,
description,
student_id,
class,
student_year

我想在teachers表上创建after insert和after update触发器。为此,我有一个名为teacherslogs的表名,包含id、teacher\u id、student\u year、class、student\u id列
所以每当记录插入teachers表时,它就应该插入teacherslogs
但对于更新后触发器面临的问题。
要求:
每当教师表中的student\u id发生变化时,我们就需要在teacherslogs中插入一个记录,同时在teachers表中插入另一个列,对这个记录进行修改,我就是这样写的

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\u year发生变化时,我们需要更新teacherslogs表中的teacher\u id和student\u 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

但最后我得到了一个例外。
这是解决我问题的正确方法还是我们能做的其他方法?

jvidinwx

jvidinwx1#

语法错误的原因是 CASE 语句需要以结尾 END CASE; ,不仅仅是 END .
我不认为 CASE 声明实际上符合您的要求,虽然好像 NEW.student_year <=> OLD.student_year 那么 NEW.class 不会被拿来和 OLD.class 查看该值是否也需要更新。这是因为(根据手册):
对于第二种语法,每个when子句search\u condition表达式都被求值,直到有一个表达式为true为止,此时执行相应的then子句语句\u 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_year 以及 classteacherlogs 应与相同 OLD.student_year 以及 OLD.class 如果它们和 NEW.student_year 以及 NEW.class 值不会更新。
如果我的理解不正确,您需要修改更新,使每个值都有条件:

ELSE
    UPDATE teacherlogs
    SET student_year = IF(NEW.student_year <=> OLD.student_year, NEW.student_year, student_year),
    class = IF(NEW.class <=> OLD.class, NEW.class, class)
    -- repeat for all columns
    WHERE student_id = OLD.student_id AND teacher_id = OLD.teacher_id;
END IF;

相关问题