mysql使用delete from where in 删除时报错如何解决

数据库存在重复的垃圾数据想利用delete from where in删除,语句如下:

DELETE FROM tms_daily_plan WHERE tms_daily_plan_id IN ( SELECT t.tms_daily_plan_id FROM tms_daily_plan t WHERE t.FIRST_PORT_CODE = 'PEK' AND t.ORG_STD BETWEEN '2019-05-08 00:00:00' AND '2019-05-08 23:59:59' GROUP BY t.TRUCK_NO );

此时报[Err] 1093 - You can't specify target table 'tms_daily_plan' for update in FROM clause的错误。

查询得知myqsl删除时in后面的子查询不能带where条件,带where条件的必须使用别名。

我们将子查询的表起个别名如下所示:

DELETE FROM tms_daily_plan WHERE tms_daily_plan_id IN ( SELECT tms_daily_plan_id FROM ( SELECT t.tms_daily_plan_id FROM tms_daily_plan t WHERE t.FIRST_PORT_CODE = 'PEK' AND t.ORG_STD BETWEEN '2019-05-08 00:00:00' AND '2019-05-08 23:59:59' GROUP BY t.TRUCK_NO ) ids );

此时成功删除。

你可能感兴趣的:(mysql)