我正在学习如何在MYSQL中构建触发器,我已经构建了一个触发器,如果其中一个部门员工被更新(他们的工资被更新或者他们被添加到部门/从部门移除),它将重新计算部门工资。如果我更新用户的工资,它也不会更新部门工资。
员工表:
SSN
Salary
Name
Dno
Supervisor_ssn
部门表:
DName
Dno
Total_sal
Manager_SSN
触发器如下所示:
DELIMITER $$
CREATE TRIGGER `Employee_AUPD` AFTER UPDATE ON `Employee` FOR EACH ROW
BEGIN
IF old.salary != new.salary THEN
UPDATE department SET total_sal = total_sal - old.salary
WHERE new.dno = department.dno;
UPDATE department SET total_sal = total_sal + new.salary
WHERE new.dno = department.dno;
END IF;
IF old.dno != new.dno THEN
UPDATE department SET total_sal = total_sal - old.salary
WHERE old.dno = department.dno;
UPDATE department SET total_sal = total_sal + new.salary
WHERE new.dno = department.dno;
END IF;
END;
DELIMITER;
答案 0 :(得分:0)
您有逻辑错误。如果工资和部门发生变化,则第一个IF块会从新部门中减去旧工资。
但你不需要测试任何东西。只需对这两个更新语句进行编码:
UPDATE department SET
total_sal = total_sal - old.salary
WHERE department.dno = old.dno;
UPDATE department SET
total_sal = total_sal + new.salary
WHERE department.dno = new.dno;
这种逻辑是睿智的,不会失败。