如何删除没有主键的表中的重复记录?
http://www.oracle.com.cn/cgi-bin/topic_show.cgi?id=4983&h=1&bpg=1&age=0
http://www.oracle.com.cn/cgi-bin/topic_show.cgi?id=4873&h=1#16842
http://www.oracle.com.cn/cgi-bin/topic_show.cgi?id=4394&h=1#14785
http://www.oracle.com.cn/cgi-bin/topic_show.cgi?id=4983&h=1&bpg=1&age=0
http://www.oracle.com.cn/cgi-bin/topic_show.cgi?id=4873&h=1#16842
http://www.oracle.com.cn/cgi-bin/topic_show.cgi?id=4394&h=1#14785
1、Windows NT4.0+ORACLE 8.0.4
2、ORACLE安装路径为:C:\ORANT问题提出:
1、当我们想要为一个表创建唯一索引时,如果该表有重复的记录,则无法创建成功。
方法原理:
1、Oracle中,每一条记录都有一个rowid,rowid在整个数据库中是唯一的,
rowid确定了每条记录是在ORACLE中的哪一个数据文件、块、行上。2、在重复的记录中,可能所有列的内容都相同,但rowid不会相同,所以只要确定出重复记录中
那些具有最大rowid的就可以了,其余全部删除。3、以下语句用到了3项技巧:rowid、子查询、别名。实现方法:
SQL> create table a (
2 bm char(4), --编码
3 mc varchar2(20) --名称
4 )
5 /表已建立.SQL> insert into a values('1111','1111');
SQL> insert into a values('1112','1111');
SQL> insert into a values('1113','1111');
SQL> insert into a values('1114','1111');SQL> insert into a select * from a;插入4个记录.SQL> commit;完全提交.SQL> select rowid,bm,mc from a;ROWID BM MC
------------------ ---- -------
000000D5.0000.0002 1111 1111
000000D5.0001.0002 1112 1111
000000D5.0002.0002 1113 1111
000000D5.0003.0002 1114 1111
000000D5.0004.0002 1111 1111
000000D5.0005.0002 1112 1111
000000D5.0006.0002 1113 1111
000000D5.0007.0002 1114 1111查询到8记录.
查出重复记录
SQL> select rowid,bm,mc from a where a.rowid!=(select max(rowid) from a b where a.bm=b.bm and a.mc=b.mc);ROWID BM MC
------------------ ---- --------------------
000000D5.0000.0002 1111 1111
000000D5.0001.0002 1112 1111
000000D5.0002.0002 1113 1111
000000D5.0003.0002 1114 1111删除重复记录
SQL> delete from a a where a.rowid!=(select max(rowid) from a b where a.bm=b.bm and a.mc=b.mc);删除4个记录.SQL> select rowid,bm,mc from a;ROWID BM MC
------------------ ---- --------------------
000000D5.0004.0002 1111 1111
000000D5.0005.0002 1112 1111
000000D5.0006.0002 1113 1111
000000D5.0007.0002 1114 1111
那如果是在sqserver中没有rowid,又该怎么办呢?
insert into <your_tmp_table> ( select distinct * from <your_table>);
delete from <your_table>;
insert into <your_table> (select * from <your_tmp_table>);
然后delete 就可以了