我应该如何修改触发器,以便可以根据他们的部门获得Total_employee?

时间:2018-11-29 05:36:06

标签: mysql database-trigger

表如下。

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);

这是触发器,我希望它显示每个部门的员工总数。

delimiter $$
create trigger department_wise_total_employee_counting
after insert on employees 
for each row begin update departments set total_employees=total_employees+1
where department_id=department_id; end$$ delimiter ;

INSERT INTO `departments` 
VALUES 
(1,'HRM',0),(2,'Accounting',0);
INSERT INTO `employees` 
VALUES 
(1,'bh@gmail.com','A','B','HRM'),
(2,'ak@gmail.com','C','D','HRM'),
(3,'mr@gmail.com','E','F','HRM'), 
(4,'pr@gmail.com','G','H','Accounting');

运行以下查询时:

select * from departments;

我得到了这个输出,它仅给出了雇员总数而不是每个部门的总数。 enter image description here

我正在尝试使HRM的total_employees = 3,而会计部门的total_employees = 1。 将不胜感激任何建议。

1 个答案:

答案 0 :(得分:2)

正如@ P.Salmon所指出的那样,通常您不应存储可以轻松计算的数据。对于此应用程序,VIEW(由@TamilSelvanC建议)是一个很好的解决方案。例如:

CREATE VIEW departments_view AS
SELECT d.department_id, d.department_name, COUNT(e.employee_id) AS total_employees
FROM departments d
LEFT JOIN employees e ON e.department_name = d.department_name
GROUP BY d.department_id;
SELECT * FROM departments_view

输出:

department_id   department_name     total_employees
1               HRM                 3
2               Accounting          1
3               Engineering         0

Demo on dbfiddle