我有一个名为employee的表。 我还有另外两个表,名为hrm,accounting。 我想根据员工所在部门将其插入人力资源和会计表。
CREATE TABLE employees (
employee_id INT(4) NOT NULL AUTO_INCREMENT,
employee_first_name VARCHAR(30) NOT NULL,
employee_last_name VARCHAR(30) NOT NULL,
employee_department VARCHAR(30) NOT NULL,
PRIMARY KEY (employee_id));
根据employee_department,我想将该雇员插入到该特定表中。
CREATE TABLE hrm (
employee_id INT(4),
employee_designation VARCHAR(20),
FOREIGN KEY (employee_id)
REFERENCES employees (employee_id)
ON DELETE CASCADE);
CREATE TABLE accounting (
employee_id INT(4),
employee_designation VARCHAR(20),
FOREIGN KEY (employee_id)
REFERENCES employees (employee_id)
ON DELETE CASCADE);
如果employee_department是hrm,我希望该雇员插入到hrm表中,如何通过mysql触发器或存储过程来做到这一点?
答案 0 :(得分:1)
尝试这样的事情:
CREATE DEFINER = CURRENT_USER TRIGGER `employees_AFTER_INSERT` AFTER INSERT ON `employees`
FOR EACH ROW
BEGIN
IF NEW.employee_department = 'hrm' THEN
INSERT INTO hrm
(employee_id, employee_designation)
VALUES
(NEW.employee_id, /*whatever you add here*/);
END IF;
END
我将解释一些关键点:
AFTER INSERT
触发器中,您可以使用NEW
获取插入值。因此,这里:NEW.employee_department
等于新雇员插入的employee_department
值,与NEW.employee_id
相同(对于AFTER DELETE
触发器,您可以使用OLD
,对于{ {1}}的更新值是AFTER UPDATE
,更新前的值是NEW
)OLD
是否等于“ hrm”:如果是,则在hrm表中插入,否则触发器执行没事