删除所有但保留一条相同记录的SQL语句如何写?详细请进!!!

MAX°孟兆 2004-08-23 07:53:07
一个表,字段(ID,F1,F2,F3),ID为自增字段,其它字段值都可以重,如:
1,a,1a,cc
2,a,1a,ccc
3,b,1a,cccc
4,b,1b,ccccc
5,b,1b,cccccc
6,b,1b,ccccccc
7,c,2c,cccccccc

现在我想删除表中所有f1相同且f2相同的记录,并只保留其中的一条,这个操作的SQL如何写?
...全文
225 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
pbsql 2004-08-23
  • 打赏
  • 举报
回复
不会,只会删除6,肯定是你自己搞错数据了
yesterday2000 2004-08-23
  • 打赏
  • 举报
回复
主要是看楼主想保留那条记录????
MAX°孟兆 2004-08-23
  • 打赏
  • 举报
回复
这组数据测试结果好像有问题,1也会被删除
1,a,1a,cc
2,b,1a,ccc
3,c,1a,cccc
4,d,1a,ccccc
5,e,1a,cccccc
6,f,2b,cc
7,f,2b,cc
pbsql 2004-08-23
  • 打赏
  • 举报
回复
保留:
2
3
6
7
pbsql 2004-08-23
  • 打赏
  • 举报
回复
写错了点,应该这样:
delete from t where exists(select * from t a where a.f1=t.f1 and a.f2=t.f2 and a.id>t.id)

下面是测试语句:
create table #t(ID int,F1 varchar(20),F2 varchar(20),F3 varchar(20))
insert into #t(ID,F1,F2,F3)
select 1,'a','1a','cc' union
select 2,'a','1a','ccc' union
select 3,'b','1a','cccc' union
select 4,'b','1b','ccccc' union
select 5,'b','1b','cccccc' union
select 6,'b','1b','ccccccc' union
select 7,'c','2c','cccccccc'
delete from #t where exists(select * from #t a where a.f1=#t.f1 and a.f2=#t.f2 and a.id>#t.id)
select * from #t
drop table #t
zjcxc 元老 2004-08-23
  • 打赏
  • 举报
回复

delete a
from 表 a left join(
select id=min(id) from 表 group by f1,f2
)b on a.id=b.id
where b.id is null
pisces007 2004-08-23
  • 打赏
  • 举报
回复
delete from yourtable
where id in
(select L.id from yourtable L join yourtable R
on L.f1=R.f1 and L.f2=R.f2 where L.id>R.id)
MAX°孟兆 2004-08-23
  • 打赏
  • 举报
回复
不行,还有一些删除不了。。。

要保留一条的情况如何解决?
要执行删除后表中的记录为:
1,a,1a,cc
3,b,1a,ccc
7,c,2c,cccc

pbsql 2004-08-23
  • 打赏
  • 举报
回复
delete from t where exists(select * from t a where a.f1=t.f1 and a.f2=t.f2 and a.id<>t.id)

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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