sql : You can't specify target table '表名' for update in FROM clause

bus_customer是主表。bus_customer_info_student是副表。bus_customer_info_student表中存了外键

刚开始查询错误数据的时候是正常的

SELECT istu.* FROM `bus_customer` c
left join bus_customer_info_student istu on c.id = istu.customer_id
 where c.is_del =0 and c.customer_type_id = 1
and istu.id is null

想删除的时候就提示错误了:

delete from bus_customer where id in(
(SELECT c.id id FROM `bus_customer` c
left join bus_customer_info_student istu on c.id = istu.customer_id
 where c.is_del =0 and c.customer_type_id = 1
and istu.id is null)

You can't specify target table for update in FROM clause。意思是说,不能先select出同一表中的某些值,再update这个表(在同一语句中)改成酱婶儿的就好了

delete from bus_customer where id in(
SELECT a.id from
(SELECT c.id id FROM `bus_customer` c
left join bus_customer_info_student istu on c.id = istu.customer_id
 where c.is_del =0 and c.customer_type_id = 1
and istu.id is null) a)

但是在删的时候还会提示:有外键不能删除   的提示,那么就用下面的sql改一下

SELECT @@FOREIGN_KEY_CHECKS; -- 查询外键状态

SET FOREIGN_KEY_CHECKS = 0;-- 设置变量,关闭唯一性校验 

然后就可以删除了。删完再把变量还原回去

SET FOREIGN_KEY_CHECKS=1;

 

 

 

你可能感兴趣的:(代码常用知识,You,can't,specify,target,table)