如何用一條sql語句刪除表中所相同的記錄
刪除重復數據
一、具有主鍵的情況
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
————————————————————————————————————————————
在數據庫里表的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號最大的那條記錄
將其余的相同記錄刪除。
|