You can’t specify target table
今天在批量删除记录时出现You can’t specify target table ‘threaddet’ for update in FROM clause错误提示。
语句如下:
delete from threaddet where id in (SELECT m.id FROM `threaddet` m left outer join `filedmsg` f on (m.filemsgid = f.id) WHERE f.id is null)
后查找网络得到错误原因为:
不能先select出同一表中的某些值,再delete这个表(在同一语句中)。
使用oracle时常常这样写,但mysql是不支持此种用法。后改用网友的子集方式,搞定此问题。
改进后的语句:
delete from threaddet where id in (select a.id from (SELECT m.id FROM `threaddet` m left outer join `filedmsg` f on (m.filemsgid = f.id) WHERE f.id is null) a)
解释:
将 (SELECT m.id FROM `threaddet` m left outer join `filedmsg` f on (m.filemsgid = f.id) WHERE f.id is null) 作为子集,然后再 select a.id from 子集,这样就不会 select 和 delete 都是同一个表。
参考:
http://www.cnblogs.com/chy1000/archive/2010/03/02/1676282.html