Is it possible to insert a value from one table to another on the basis of value using trigger?

末鹿安然 提交于 2019-12-11 15:58:13

问题


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 using NEW. So here : NEW.employee_department is equal to the inserted employee_department value of the new employee, same for NEW.employee_id (for AFTER DELETE trigger you can use OLD and for AFTER UPDATE you have NEW for the updated value and OLD 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!