解决MySQL Update:You can't specify target table for update in FROM clause

巧了我就是萌 提交于 2019-11-30 12:53:25

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

update 
    tms_jyxx_mx 
set 
    gg_dm = '1004' 
where 
    jyxx_id 
in 
    (SELECT
        t1.jyxx_id as jyxx_id
    FROM
        tms_jyxx t1,
        tms_jyxx_mx t2
    WHERE
        t1.sjmc = '保定白沟新城铭磊加油站'
    AND t1.jyxx_id = t2.jyxx_id
    AND t2.ljqh = '14'
    AND t2.jysj >= '2019-04-30 10:17:22'
    AND t2.jysj <= '2019-09-26 23:59:59'
    ORDER BY
        t2.jysj
    desc)

改成下面的就行了:

update 
    tms_jyxx_mx 
set 
    gg_dm = '1004' 
where 
    jyxx_id 
in 
    (SELECT
        tt.jyxx_id
    from
    (SELECT
        t1.jyxx_id as jyxx_id
    FROM
        tms_jyxx t1,
        tms_jyxx_mx t2
    WHERE
        t1.sjmc = '保定白沟新城铭磊加油站'
    AND t1.jyxx_id = t2.jyxx_id
    AND t2.ljqh = '14'
    AND t2.jysj >= '2019-04-30 10:17:22'
    AND t2.jysj <= '2019-09-26 23:59:59'
    ORDER BY
        t2.jysj
    desc) tt)

也就是说将select出的结果再通过中间表select一遍,这样就规避了错误。注意,这个问题只出现于MySQL,MsSql和Oracle不会出现此问题。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!