MySQL触发器在另一个字段中插入两个字段的总和

时间:2014-11-26 07:08:37

标签: mysql triggers insert

我一直在使用MySQL安静。但我对MySQL触发器完全不熟悉。

Student Table
---------------------------------------------------------
| midterm | final | second_chance | third_chance | total |
---------------------------------------------------------
|   20    |  80   |               |              |  100  |
---------------------------------------------------------
|   15    |  70   |               |              |  85   |
---------------------------------------------------------

考虑到上表,我想要触发器执行以下操作:
在表上的每个INSERT或UPDATE之后,触发器应检查是否设置了third_chance值,如果是,则插入(midterm + third_chance)到total OTHERWISE,它应该检查是否设置了second_chance值;如果设置了第二次机会,则插入(second_chance + midterm);最后如果这两个(second_chance和third_chance)没有设置insert(midterm + final)为total。

2 个答案:

答案 0 :(得分:1)

这可以通过触发器完成:

DELIMITER $$

CREATE TRIGGER mytable_bu
BEFORE UPDATE ON mytable
FOR EACH ROW
BEGIN
   SET NEW.total = NEW.midterm + 
                   COALESCE(NEW.third_chance, NEW.second_chance, NEW.final);
END$$

DELIMITER ;

total 始终基于其他列计算的事实可能表明它根本不应该是表中的列。相反,它可以是视图中的计算列:

CREATE students_view AS
SELECT s.*, 
       midterm + COALESCE(third_chance, second_chance, final) AS total
FROM   students.s

答案 1 :(得分:0)

请检查 BEFORE INSERT BEFORE UPDATE ,而不是之后。

例如,像这样:

DELIMITER $$

CREATE TRIGGER mytable_bu
BEFORE UPDATE ON mytable
FOR EACH ROW
BEGIN
   IF NEW.third_chance IS NOT NULL THEN
      SET NEW.total = NEW.midterm + NEW.third_chance;
   ELSEIF NEW.second_chance IS NOT NULL THEN
      SET NEW.total = NEW.midterm + NEW.second_chance;
   ELSE
      SET NEW.total = NEW.midterm + NEW.final;
   END IF;
END$$

DELIMITER ;

您还需要类似的 BEFORE INSERT 触发器。