Search code examples
mysqltriggersmysql-workbenchworkbench

inserting values from another table via a TRIGGER in MYSQL


I need to create a trigger when a new record is added to the "plan" table, a record is automatically created in the "results" table. Table "Plan" has columns:

  • IdService
  • IdEmployee
  • Groupe
  • Date
  • Type (varchar)

Table "Results" has columns:

  • IdService
  • IdEmployee
  • IdClient
  • Date
  • Result (varchar) But the idClient must be taken from table "Clients", corresponding to the group number added to the plan. Thus, the trigger should create not one, but several rows in the result table (since there can be several clients in one group)

I am attaching my code, but there is obviously an error in it

CREATE DEFINER = CURRENT_USER TRIGGER `mydb`.`Plan_AFTER_INSERT` AFTER INSERT ON `Plan` FOR EACH ROW
BEGIN
insert into results (Result, idClient, Date, idService, idEmployee)
 values ('в процессе',idClient = (Select idClient from Clients
where Clients.Groupe = Plan.New.Groupe),
NEW.Date, NEW.idService, NEW.idEmployee);
END

Solution

  • It is quite OK only your subquery has ti return only one row, so it is better to limit it

    DELIMITER //
    CREATE DEFINER = CURRENT_USER TRIGGER `mydb`.`Plan_AFTER_INSERT` AFTER INSERT ON `Plan` FOR EACH ROW
    BEGIN
    insert into results (Result, idClient, Date, idService, idEmployee)
     values ('в процессе',(Select idClient from Clients
    where Clients.Groupe = New.Groupe ORDER BY idClient LIMIT 1),
    NEW.Date, NEW.idService, NEW.idEmployee);
    END//
    DELIMITER ;