问题
I've a table named employee. I've two other tables named hrm, accounting. I want to insert the employee into hrm and accounting table according to their departments.
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));
according to the employee_department, I want to insert that employee to that particular table.
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);
if employee_department is hrm, I want that employee to get inserted into hrm table, how can i do it through mysql trigger or stored procedure?
回答1:
Try something like this :
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
I will explain some key point :
- In an
AFTER INSERT
trigger, you can get the inserted valued usingNEW
. So here :NEW.employee_department
is equal to the insertedemployee_department
value of the new employee, same forNEW.employee_id
(forAFTER DELETE
trigger you can useOLD
and forAFTER UPDATE
you haveNEW
for the updated value andOLD
for the value before the update) - In a MySQL trigger, you can add condition : here I check if the new
employee_department
of the new employee is equal to "hrm" : if YES THEN do an insert in your hrm table, ELSE the trigger do nothing - If you want to do the same for "accounting", the logic will be the same
来源:https://stackoverflow.com/questions/52850729/is-it-possible-to-insert-a-value-from-one-table-to-another-on-the-basis-of-value