gpt4 book ai didi

mysql - 我该如何修改我的触发器,以便我可以根据部门获取total_employees?

转载 作者:行者123 更新时间:2023-11-29 06:36:42 25 4
gpt4 key购买 nike

下表给出。

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

我正在尝试为人力资源管理设置total_employees=3,为会计设置total_employees=1。如果有任何建议,我们将不胜感激。

最佳答案

正如 @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

关于mysql - 我该如何修改我的触发器,以便我可以根据部门获取total_employees?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53532486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com