转载自:https://blog.csdn.net/Warpar/article/details/72983835
一、数据库中的去重操作(删除数据库中重复记录的SQL语句)主要有三种方法
(1)、rowid方法
(2)、group by 方法
(3)、distinct方法
1、用rowid方法
(1).在oracle中,每一条记录都有一个rowid,rowid在整个数据库中是唯一的,rowid确定了每条记录是在Oracle中的哪一个数据文件、块、行上。
(2).在重复的记录中,可能所有列的内容都相同,但rowid不会相同,所以只要确定出重复记录中那些具有最大rowid的就可以了,其余全部删除。
根据Oracle
带的rowid
属性(mysql中没有),可以进行判断是否存在重复语句;
(1)、查出表1和表2中name相同的数据
select * from table1 a
where rowid !=(select max(rowid) from table2 b
where a.name1 = b.name1 and a.name2 = b.name2)
(2)、删除表1和表2 中name相同的所有数据
delete from table1 a
where rowid !=(select max(rowid) from table2 b
where a.name1 = b.name1 and a.name2 = b.name2)
2、用group by方法
主要用于分组统计,一般都是使用在聚合函数中使用;
(1)、查数据
select count(num), max(id) from student 返回分组后的每组的总数和最大id,
group by num having count(num)>1 根据num分组后找出表中num列出现次数大于一次的。
(2)、删除数据
删除表中num列所有重复的数据
delete from student where num in (
select temp.num from (
select num from student group by num having count(num)>1
) temp)
不能从“子句”中直接指定要“更新”的目标表student
3、用distinct方法
一般用于比较小的表进行去重,会过滤掉多余的重复记录,返回不重复的记录或字段;
select distinct name from student;//单列去重
select distinct name,age,gender from student;//满足三列同时相同时去重