关于数据库mysql查询的一点问题?
功能是:删除除了id号不同,其他都相同的冗余信息
select min(id) mid from student2 group by name) as t;
select mid from (select min(id) mid from student2 group by name) as t;
上面两句话执行出来的结果都是一样,结果如下。
+------+
| mid |
+------+
| 1 |
| 2 |
+------+
那为什么我下面两句就会出错呢?
delete from student2 where id not in(select min(id) mid
from student2 group by name );
delete from student2 where id not in(select mid from (select min(id) mid
from student2 group by name) as t);
------解决方案--------------------在更新或删除目标表中数据的时候如果使用子查询,目标表不能在子查询的From语句中出现~
create table tmp as
select min(id) as id mid
from student2 group by name
delete from student2 where id not in(select id from tmp );
delete from student2 where id not in( select * from (select mid from (select min(id) mid
from student2 group by name) as tmp );
mysql有这么个特性,对于更新操作,是不允许对统一表进行子查询的,也就是
delete from student2 where id not in(select min(id) mid
from student2 group by name );----这个是不行的delete from student2 where id not in(select mid from (select min(id) mid
from student2 group by name) as t);-