如何用一条SQL语句删除表中所相同的记录?

leayh 2003-10-17 01:06:21
同题
...全文
80 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
leayh 2003-10-20
  • 打赏
  • 举报
回复
我没有用到rowid。
521521xo 2003-10-17
  • 打赏
  • 举报
回复
在数据库里表的rowid是唯一的所以相同的记录rowid是不同的可以分两步做因为
一:查重复记录
select rowid,bm,mc from 表名1 where 表1.rowid!=(select max(rowid) from
表1 b(别名) where 表1.bm=b.bm and 表.mc=b.mc);
二:删除重复记录
delete from 表1 where 表1.rowid!=(select max(rowid) from 表1.b where 表1.bm=b.bm and 表1.mc=b.mc);
这段SQL的功能是查找重复的记录,然后保留rowid号最大的那条记录 将其余的相同记录删除。
leayh 2003-10-17
  • 打赏
  • 举报
回复
这有区别吗?有可能是一条记录中几个关键字段相同,也有可能是所有的字段都相同才算重复的记录。
yujohny 2003-10-17
  • 打赏
  • 举报
回复
你这样的要求,那真是没办法实现
520zyb 2003-10-17
  • 打赏
  • 举报
回复
具体是多少相同,是一个字段名相同的记录,还是所有字段都相同的记录呢?
leayh 2003-10-17
  • 打赏
  • 举报
回复
我的意思是不能先删除原表,再建新表。
另外,你的有主键存在的方法跟本不能实现啊,结果是(0 row(s) affected)。
注:我的是没有主键。
yoki 2003-10-17
  • 打赏
  • 举报
回复
删除重复数据

一、具有主键的情况
a.具有唯一性的字段id(为唯一主键)
delete table
where id not in
(
select max(id) from table group by col1,col2,col3...
)
group by 子句后跟的字段就是你用来判断重复的条件,如只有col1,
那么只要col1字段内容相同即表示记录相同。

b.具有联合主键
假设col1+','+col2+','...col5 为联合主键
select * from table where col1+','+col2+','...col5 in (
select max(col1+','+col2+','...col5) from table
where having count(*)>1
group by col1,col2,col3,col4
)
group by 子句后跟的字段就是你用来判断重复的条件,
如只有col1,那么只要col1字段内容相同即表示记录相同。

c:判断所有的字段
select * into #aa from table group by id1,id2,....
delete table
insert into table
select * from #aa

二、没有主键的情况

a:用临时表实现
select identity(int,1,1) as id,* into #temp from ta
delect #temp
where id not in
(
select max(id) from # group by col1,col2,col3...
)
delete table ta
inset into ta(...)
select ..... from #temp

b:用改变表结构(加一个唯一字段)来实现
alter table 表 add newfield int identity(1,1)
delete 表
where newfield not in
(
select min(newfield) from 表 group by 除newfield外的所有字段
)

alter table 表 drop column newfield





22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧