先上表(第一次发帖,比较丑望大家莫怪)
在做练习题中遇到这个题目:“删除除了编号不同, 其他都相同的学生冗余信息”
一开始想的是:先用子句用分组形势把数据去重查出去重后的bh,然后delete from XXXX表 where bh not in (子句)
结果神奇的来了
子句是可以查出数据的
但是加上not in 之后显示没数据了
于是测试了一下,这样是可以的
目前不知道问题出在哪里,望大神们指导一下,谢谢!
delete from student where bh not in(select * from (select min(bh) as bh from student group by xh,xm,kcbh,kcmc,score) t);
相关的查询,一般来说我们都是使用group by + having + order 实现的。
你这groupby 一大串干啥,使用子查询试试
简化写了下思路, 你自己修改吧
-- 1.查询重复记录的数据,重复记录大于1
select s.xh from student s group by xh,score
having count(*)>1;
-- 2.询重复记录的数据,重复记录大于1,得到重复记录中最小的ID
select min(s.bh) from student s group by xh,score
having count(*)>1;
-- 整理结果: 需删除的数据,属于重复数据,且不是重复数据中ID最小的数据,
select * from student s
where s.xh in (select t.xh from student t group by xh,score
having count(*)>1)
and s.bh not in (select min(d.bh) from student d group by xh,score
having count(*)>1)
补充:作者你题目中提到的 select bh from student group by xh,xm,kcbh,kcmc,score; 这个SQL 不会报错吗? group by 函数或者分组里的字段才能被查询,bh 不属于group by 分组的字段,所以我觉得你这个SQL会报错才对