MySQL delete嵌套子查询问题

表数据如下:


class=1下的数据:


class=2下的数据:


class=1独有的数据:

select * from tb_student_1 WHERE class=1 and student_name not in(select student_name from tb_student_1 WHERE class=2)


现在想从表中将class1独有的数据删掉,如果直接使用上面的查询语句嵌套在delete语句中:

DELETE from tb_student_1 where student_name in(select student_name from tb_student_1 WHERE class=1 and student_name not in(select student_name from tb_student_1 WHERE class=2))

此时mysql会报如下错误:

[Err] 1093 - You can't specify target table 'tb_student_1' for update in FROM clause

也就是不能先从同一张表中查出数据,再在同一张表中进行update操作


解决办法:

创建临时表

create table tmp as (select student_name from tb_student_1 WHERE class=1 and student_name not in(select student_name from tb_student_1 WHERE class=2))


#从临时表中查找数据并从student表中删除
DELETE from tb_student_1 where student_name in(select student_name from tmp)

#将临时表删除
drop table if exists tmp


参考:

priestmoon 

mysql中You can't specify target table for update in FROM clause错误


孫瑞

MySQL中嵌套子查询删除出错解决方案


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值