MySQL报You can't specify target table for update in FROM clause

发布时间:2021/10/18 作者:天马行空 阅读(860)

MySQL报You can't specify target table for update in FROM clause错误的意思是说,不能先select出同一表中的某些值,再update这个表。就如下面的语句:

UPDATE gc_com_post as a SET a.comment_count=(
SELECT COUNT(*) as total FROM gc_com_post as b WHERE b.`status`=1 and b.to_reply_id=a.id
) WHERE a.`status`=1


出现这种问题的时候我们可以利用一张中间表来解决,这样就规避了错误,可以做如下修改:

UPDATE gc_com_post as a SET a.comment_count=(
    SELECT total from (
        SELECT b.to_reply_id,COUNT(*) as total FROM gc_com_post as b WHERE b.`status`=1 GROUP BY b.to_reply_id
    ) as c WHERE c.to_reply_id=a.id
) 
WHERE a.`status`=1


关键字mysql sql error