SQL中的如何把多条一样的记录删除只留一条

来源:百度知道 编辑:UC知道 时间:2024/05/22 03:26:34
不小心在表中添加了N条一样的记录,我想用delete把它删除了只留下一条就要以,呵呵,搞了好久都没有搞定了,请大家多多指教了。

表名 tb1
字段名(主键) ID

假设表TB1里的数据都是重复的,只留一条
delete tb1 where ID not in (select top 1 from tb1)

如果还有别的记录的话后面加上条件

如果表没有唯一能标识该行记录的字段,比如自增列,那么就只能将表中全部数据排重后放入临时表,然后再重新导入。
比如
select distinct *
into #temp
from 表

truncate table 表

insert into 表
select *
from #temp

三楼的:delete tb1 where ID not in (select top 1 from tb1)
这只能针对少量的操作:如果是大量的相同数据操作就如一楼所说。
insert into 表 select * from #temp

也可以改写为
select * into 原表名 from #temp
增加以下
drop #temp

sql中只能全部删除同样的记录,oracle中可以不全部删除同样的记录