I have two tables employee and department. They are linked with dep_id column, which is a primary key in departments and a foreign key in employee.
My goal is to:
Update salaries of all employees whos salaries are above average salary in their department. Right now I have 2 queries to do this:
UPDATE employee E
SET E.payroll = E.payroll + 1000
WHERE E.payroll > (SELECT AVG(E2.payroll) FROM employee E2 WHERE E.dep_id = E2.dep_id)
I get an error: #1093 - Table 'E' is specified twice, both as a target for 'UPDATE' and as a separate source for data
2) In department table I store the amount of employees per department and a total payroll they have per department
UPDATE employee E
SET E.payroll = E.payroll + 1000
WHERE E.payroll > (SELECT department.dep_payroll / department.dep_amount FROM department WHERE department.dep_id = E.dep_id)
This one works fine, but because I have a trigger which fires after\before (I checked both ways) updating employee table and updates dep_payroll it blocks me from executing 2nd query giving this error #1442 - Can't update table 'department' in stored function/trigger because it is already used by statement which invoked this stored function/trigger. Here it is
CREATE TRIGGER `t3` BEFORE UPDATE ON `employee`
FOR EACH ROW UPDATE department
SET dep_payroll = dep_payroll - OLD.payroll + NEW.payroll
WHERE dep_id = NEW.dep_id
How can I execute an update query?