简体   繁体   中英

Update with SubQuery from same table

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);

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM