MySQL 中 delete where in 语句的子查询限制

根据ID删除数据,代码如下:

DELETE
FROM
	t_swcas_db_sync_send_task
WHERE
	id IN (
		SELECT
			b.id AS id
		FROM
			t_swcas_db_old_part_back a
		INNER JOIN t_swcas_db_sync_send_task b ON a.ID = b.REF_ID
		WHERE
			WARRANTY_PARTS_STATUS = '已收货'
	)

执行异常信息

[Err] 1093 - You can’t specify target table ‘t_swcas_db_sync_send_task’ for update in FROM clause

#SQL调整

DELETE
FROM
	t_swcas_db_sync_send_task
WHERE
	id IN (
		SELECT
			id
		FROM
			(
				SELECT
					b.id AS id
				FROM
					t_swcas_db_old_part_back a
				INNER JOIN t_swcas_db_sync_send_task b ON a.ID = b.REF_ID
				WHERE
					WARRANTY_PARTS_STATUS = '已收货'
			) AS n
	)

执行成功

原因分析

in 条件里的查询结果需要 重命名才能语法通过。

再试一下查询

select * 
FROM
	t_swcas_db_sync_send_task
WHERE
	id IN (

				SELECT
					b.id AS id
				FROM
					t_swcas_db_old_part_back a
				INNER JOIN t_swcas_db_sync_send_task b ON a.ID = b.REF_ID
				WHERE
					WARRANTY_PARTS_STATUS = '已收货'
	)

没问题,不知道删除为什么要限制,查询不限制。。不纠结,记录下这个坑。。。

你可能感兴趣的:(数据库,mysql)