求助SQL:如何删除重复数据

来源:百度知道 编辑:UC知道 时间:2024/06/20 13:13:20
哪位大虾能帮我写条SQL:表里有N条记录,其中有些是重复的,我想把重复的部分删掉,及每条记录只有一条记录存在表中!谢谢

例如:记录虽然存在重复,但是rowid是唯一的,所以在子查询取得重复行中最小的rowid,删除重复行中
大于最小的rowid的行,只是保留了最小rowid的行,就是删除了重复行。
这个语句如果要调优的话,可以在内部查询中建索引

delete from ttt a where rowid>(select min(rowid) from ttt b where a.name=b.name);

select 字段1,字段2,字段3 from table group by 字段1,字段2,字段3 having count(*)>1
用上边这句能找出所有重复的数据
字段1,2,3你替换成你表里的字段名,如果有更多字段的话,你就继续添加,最后group by的时候不要忘记了
删除的时候要建立一个临时表
create table new_table as select 字段1,字段2,字段3 from old_table group by 字段1,字段2,字段3;
然后删除原表数据
truncate table old_table;
然后把临时表数据反插回去
insert into new_table select * from old_table;

去掉重复数据,把没有重复的数据放在临时表#table中
select distinct *
into #table
from
tablename
删除原数据
truncate table tablename
恢复数据
insert into tablename
select *
from
#table

你使用的是什么数据库?不同的数据库有不同的解决方案