MySQL update中使用select:You can't specify target table 'xxx' for update in FROM clause 问题

【问题】想通过update更新某个查询的合计值,这样就可以不用查询两次了(一个查询统计总数,一个更新表中的数据)

【原因】update语句不能包含select的查询结果

不能通过

update a set a.xx= (select xx from b) 

必须使用 join 进行连接

update a left join (select xx from b) c on 1=1 set a.xx = c.xx
--
update a inner join (select yy from b) c set a.xx = c.xx

【解决】通过 left join 来实现更新查询数据

UPDATE 
    task_info ti
LEFT JOIN 
    ( SELECT count( 1 ) AS 'num' FROM task_info WHERE del_flag = 0 AND parent_id = 63310 ) t 
ON 
    1 = 1 
SET 
    ti.subtasks = t.num 
WHERE
    id = 63310

 

posted @ 2022-09-17 13:31  changlinlo  阅读(75)  评论(0编辑  收藏  举报