0

Is it possible to update using a subquery from the same table?

I get this error:

1093 - You can't specify target table 'tasks' for update in FROM clause

update tasks SET completed_form = 'y' AND all_forms_in = 'y' where EID in (select EID from tasks WHERE completed_form = 'y' AND all_forms_in = 'n' group by EID having count(*) > 1);

UPDATE

I found that if I wrapped the query in another select it worked. As referenced here: MySQL Error 1093 - Can't specify target table for update in FROM clause

update tasks SET all_forms_in = 'y' where EID in (SELECT * FROM (select EID from tasks WHERE completed_form = 'y' AND all_forms_in = 'n' group by EID having count(*) > 1)AS b);
Community
  • 1
  • 1
osakagreg
  • 537
  • 4
  • 19

1 Answers1

1

MySQL supports JOIN in UPDATE statements, so you could do this without subqueries. You'd have to join to two distinct rows with your completed criteria to simulate the count(*) > 1.

UPDATE tasks AS t1
INNER JOIN tasks AS t2
  ON (t1.EID = t2.EID AND t2.completed_form = 'y' AND t2.all_forms_in = 'n')
INNER JOIN tasks AS t3
  ON (t1.EID = t3.EID AND t3.completed_form = 'y' AND t3.all_forms_in = 'n'
  AND t2.primary_key <> t3.primary_key)
SET t1.completed_form = 'y', 
    t1.all_forms_in = 'y';
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828