I am working on a problem in which I have to use the table I want to update in a subquery. Can you help me find a solution?
UPDATE employees_clients AS ec2
SET ec2.employee_id = (CASE WHEN ec2.client_id = ec2.employee_id
THEN (SELECT e.id
FROM clients AS c
JOIN employees_clients AS ec
ON ec.client_id = c.id
JOIN employees AS e
ON e.id = ec.employee_id
GROUP BY e.id
ORDER BY count(e.id),e.id
LIMIT 1)
END);
Error Code: 1093. You can't specify target table 'ec2' for update in FROM clause
I found a solution to the problem I created a virtual table.
CREATE VIEW v_employee_with_min_clients AS
SELECT e.id
FROM clients AS c
JOIN employees_clients AS ec
ON ec.client_id = c.id
JOIN employees AS e
ON e.id = ec.employee_id
GROUP BY e.id
ORDER BY count(e.id),e.id
LIMIT 1;
SET SQL_SAFE_UPDATES = 0;
UPDATE employees_clients AS ecl
SET ecl.employee_id = (SELECT * FROM v_employee_with_min_clients)
WHERE ecl.client_id = ecl.employee_id;