今天要删除一批数据,大致意思是,删除表 A 数据,这些数据在表 A 存在,但是不在表 B 出现的数据,表 A 数据是表 B 数据父类。结果在执行 SQL 时报出 1093 错误,SQL 如下:
DELETE FROM 主表 WHERE id IN ( SELECT cpxh.id AS cpxh_id FROM 表1 AS a LEFT JOIN 表2 AS b ON b.xx= a.xx LEFT JOIN 表3 AS c ON c.xx= b.xx WHERE b.xx= 'xxxxx' AND a.id IS NULL )
错误代码: 1093
You can't specify target table '主表' for update in FROM clause
这样删除会报错,将 SQL 改成下面这样就可以正常执行
delete from t where id in (select * from (select id from t where id < 5) tmp)
优化 SQL 为连接查询
delete t from t join (select id from t where id < 5) tmp on t.id=tmp.id
这样也可以解决 SQL 中的1093问题。