如何添加强制同一个表中两列值相同的约束?
我希望学生班级与学生成绩匹配。
/*Student Grade = Student Class Grade constraint "BEFORE INSERT" */
delimiter //
CREATE TRIGGER StCGradeCheckBIN BEFORE INSERT ON STUDENT
FOR EACH ROW
BEGIN
IF new.Class_Grade <> Grade THEN
SIGNAL SQLSTATE '10000'
SET MESSAGE_TEXT = 'Error while filling the Class Grade faild! It is must match the Student.Grade feild';
END IF;
END;
// delimiter ;
/*Student Grade = Student Class Grade constraint "BEFORE UPDATE" */
delimiter //
CREATE TRIGGER StCGCheckBUP BEFORE UPDATE ON Student
FOR EACH ROW
BEGIN
IF new.Class_Grade <> Grade THEN
SIGNAL SQLSTATE '10000'
SET MESSAGE_TEXT = 'Error while Updating the Class Grade feild! It is must mathc the Student.Grade feild';
END IF;
END;
// delimiter ;
此触发器不起作用,在插入STUDENT表
期间会导致此错误Error Code: 1054. Unknown column 'Grade' in 'field list'
使用mysql workbench 6.3
提前致谢
答案 0 :(得分:0)
尚未发表评论,但如果两列必须相同,为什么还需要第二列?它不会用于任何目的。
答案 1 :(得分:0)
问题在于触发器无法理解Grade
。因为它们位于同一个表中,我认为您可以使用new.
来限定名称:
delimiter //
CREATE TRIGGER StCGradeCheckBIN BEFORE INSERT ON STUDENT
FOR EACH ROW
BEGIN
IF new.Class_Grade <> new.Grade THEN
--------------------------^
SIGNAL SQLSTATE '10000'
SET MESSAGE_TEXT = 'Error while filling the Class Grade faild! It is must match the Student.Grade feild';
END IF;
END;
// delimiter ;