ITPub博客

首页 > 数据库 > MySQL > mysql中,删除重复记录的方法及疑问(1)

mysql中,删除重复记录的方法及疑问(1)

原创 MySQL 作者:spaceair 时间:2005-09-17 11:02:39 0 删除 编辑
用临时过渡表,这种很笨拙的方法。请达人指导。[@more@]

如果数据库的设计不规范,某个表没有主健,那么肯定会有重复记录的现象,或者存在这种危险。在oracle中,可以通过rowid来删除重复记录。但在mysql中如何实现呢?
google一下,有个方法如下:

1、准备基表test,待测试。
create table test (c1 smallint,c2 smallint);
insert into test values(1,1);
insert into test values(1,1);
insert into test values(1,2);
insert into test values(2,2);
insert into test values(2,2);
2、创建一个临时表,结构与原表一致,但没有数据。
create table tmp as select * from test where 1=2;
3、将原表数据插入临时表,重复记录合为一条记录。
insert into tmp select distinct * from test;
4、查看一下基表和临时表的数据。
mysql> select * from test;
+------+------+
| c1 | c2 |
+------+------+
| 1 | 1 |
| 1 | 1 |
| 1 | 2 |
| 2 | 2 |
| 2 | 2 |
+------+------+
5 rows in set (0.00 sec)

mysql> select * from tmp;
+------+------+
| c1 | c2 |
+------+------+
| 1 | 1 |
| 1 | 2 |
| 2 | 2 |
+------+------+
3 rows in set (0.00 sec)

5、删除基表数据
mysql> delete from test;
Query OK, 5 rows affected (0.02 sec)
6、将临时表数据插回基表
mysql> insert into test select * from tmp;
Query OK, 3 rows affected (0.03 sec)
Records: 3 Duplicates: 0 Warnings: 0
7、查看一下基表的数据
mysql> select * from test;
+------+------+
| c1 | c2 |
+------+------+
| 1 | 1 |
| 1 | 2 |
| 2 | 2 |
+------+------+
3 rows in set (0.00 sec)
8、数据准确,完成基表重复记录的删除。

后续问题:
1、如果这个基表很大(100万、1000万条记录),还用这个方法?
2、有没有更好的办法?

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/59630/viewspace-806671/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
  • 博文量
    149
  • 访问量
    4921242