是否可以使用同一个表中的子查询进行更新?
我收到此错误:
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);
我发现,如果我将查询包装在另一个选择中,那么它是否有效。这里引用: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);
答案 0 :(得分:0)
MySQL在UPDATE语句中支持JOIN,因此您可以在没有子查询的情况下执行此操作。您必须使用已完成的条件加入两个不同的行,以模拟计数(*)> 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';