zoukankan      html  css  js  c++  java
  • mysql中删除数据的错误:You can't specify target table 'table_name' for update in FROM clause

    在MySQL中,写SQL语句的时候 ,可能会遇到You can't specify target table '表名' for update in FROM clause这样的错误,它的意思是说,不能先select出同一表中的某些值,再update这个表(在同一语句中),即不能依据某字段值做判断再来更新某字段的值。

    例如:

    delete from userscourselogs where id not in (select b.id as id from ( SELECT MAX(a.`ModifyAt`)ModifyAt,a.userid FROM userscourselogs a   GROUP BY a.UserId,a.SeriesId,a.CourseId) c INNER JOIN `userscourselogs` b ON c.userid=b.userid AND c.ModifyAt=b.ModifyAt)

    报异常:You can't specify target table 'table_name' for update in FROM clause

    将SELECT出的结果再通过中间表SELECT一遍,这样就规避了错误。

    修改为

    delete from userscourselogs where id not in (select id from (  select b.id as id from ( SELECT MAX(a.`ModifyAt`)ModifyAt,a.userid FROM userscourselogs a   GROUP BY a.UserId,a.SeriesId,a.CourseId) c
     INNER JOIN `userscourselogs` b ON c.userid=b.userid AND c.ModifyAt=b.ModifyAt) as d)

    执行成功。

    这个问题只出现于MySQL,MSSQL和Oracle不会出现此问题。

  • 相关阅读:
    洛谷 P1032 子串变换
    RCTF 2017 easyre153
    SUCTF 2016 : dMd
    南邮 base64全家桶
    洛谷 P1908 逆序对
    2019中山大学程序设计竞赛 Triangle
    WhiteHat Contest 11 : re1100
    P1010 幂次方
    洛谷 P1088 火星人
    南邮 骚年来一发吗
  • 原文地址:https://www.cnblogs.com/dayang12525/p/12744961.html
Copyright © 2011-2022 走看看