首页 > 解决方案 > What is wrong with the following trigger before an update?

问题描述

I have to implement the following trigger in mysql before an update is made on the enrollment table

Enforce the constraint that all letter grades must be one ofA, B, C, D (no +/-) in this database). Also ensure that the grade point value matches: A=4.0, B=3.0, C=2.0, D=1.0

  CREATE TABLE enrollment (
  student_id CHAR(4) not null,
  student_name VARCHAR(100) not null,
  course_id CHAR(7) not null,
  enroll_date DATE not null,
  letter_grade CHAR(2),
  grade_points DECIMAL(2,1),
  PRIMARY KEY (student_id, course_id)
);

This is what I have so far:

create trigger letter_grade_checker before update on enrollment 
for each row
  begin
    if ((new.letter_grade != 'A' and new.grade_points != 4.0)
    or (new.letter_grade != 'B' and new.grade_points != 3.0)
    or (new.letter_grade != 'C' and new.grade_points != 2.0)
    or (new.letter_grade != 'D' and new.grade_points != 1.0))
    then SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Invalid grade or grade_points provided';
    end if;
end;

Although it's not working for the following update statement:

UPDATE enrollment SET letter_grade = 'B', grade_points = 3.0
    WHERE student_id = '9999' and course_id = 'CSC-399';

标签: mysql

解决方案


你的布尔表达式应该是这样的

    if  (new.letter_grade != 'A' or new.grade_points != 4.0)
    and (new.letter_grade != 'B' or new.grade_points != 3.0)
    and (new.letter_grade != 'C' or new.grade_points != 2.0)
    and (new.letter_grade != 'D' or new.grade_points != 1.0)
    then ...

因为逻辑是

!((a AND b) OR (c AND d)) = !(a AND b) AND !(c AND d) = (!a OR !b) AND (!c OR !d)

推荐阅读