我有两个桌子。
CREATE TABLE `departments` (
department_id INT(2) NOT NULL AUTO_INCREMENT,
department_name VARCHAR(30) NOT NULL,
total_employees INT(4),
PRIMARY KEY (department_id),
UNIQUE (department_name));
CREATE TABLE `employees` (
employee_id INT(4) NOT NULL AUTO_INCREMENT,
employee_email VARCHAR(30) NOT NULL,
employee_first_name VARCHAR(30) NOT NULL,
employee_last_name VARCHAR(30) NOT NULL,
department_name VARCHAR(30) NOT NULL,
PRIMARY KEY (employee_id),
UNIQUE (employee_email),
FOREIGN KEY (department_name)
REFERENCES departments (department_name)
ON DELETE CASCADE);
现在,假设我有一个人力资源管理部门。人力资源管理部门有2名员工。因此,我希望通过触发器来获取部门表2的total_employees的值。如果能得到您的一些建议,那就太好了。
答案 0 :(得分:2)
您似乎想要一个 update 触发器,而不是一个 insert 触发器。 插入触发器将是:
delimiter $$
create trigger employee_insertion_in_individual_department
after insert on employees for each row
begin
update departments set
total_employees = total_employees + 1
where department_id = new.department_id;
end if;
end$$
delimiter ;
更新触发器将更像:
delimiter $$
create trigger employee_insertion_in_individual_department
after insert on employees for each row
begin
if not (old.employee_department <=> old.employee_department) then
update departments set
total_employees = total_employees + (case when department_id = old_department_id then -1 else 1 end)
where department_id in (old.department_id, new.department_id);
end if;
end$$
delimiter ;
答案 1 :(得分:1)
在插入触发器中,没有“旧” ...因为您要插入一行,而不是更新一行。该行没有以前的版本,因为它以前从未存在过。您可以只使用new
在新创建的行中使用department_id。而且您不需要if
,因为没有什么可比较:
delimiter $$
create trigger employee_insertion_in_individual_department
after insert on employees for each row begin
update departments set total_employees=total_employees+1
where department_id=new.department_id;
end$$ delimiter ;
另请参阅How to get inserted value for trigger
P.S。通过使用实际行数而不是简单的增量来更新它可能更安全。我担心如果几乎同时更改许多行可能会产生歪斜。可能值得测试这是否引起问题。
P.P.S。我假设您还打算出于相同的目的添加UPDATE和DELETE触发器(如果还没有的话)。