Discuz教程网

Mysql删除重复记录

[复制链接]
authicon php1314 发表于 2011-1-5 17:17:48 | 显示全部楼层 |阅读模式
有关mysql删除重复记录的方法,我在网上看到很多文章,很多是照抄的,我自己按网上的方法实验了一下,没有一个sql语句就能解决的方法,不知道有没有高手可以出招。
我试验的过程如下:
mysql> select * from duplicate;
+—-+——-+
| id | name  |
+—-+——-+
|  1 | wang  |
|  2 | wang  |
|  3 | wdang |
|  4 | wdang |
|  5 | wdand |
|  6 | wddda |
+—-+——-+
6 rows in set (0.00 sec)
select * from duplicate where id in(select min(id) from duplicate group by name);
+—-+——-+
| id | name  |
+—-+——-+
|  1 | wang  |
|  3 | wdang |
|  5 | wdand |
|  6 | wddda |
+—-+——-+
4 rows in set (0.01 sec)
mysql> delete from duplicate where id not in(select min(id) from duplicate group by name);
ERROR 1093 (HY000): You can’t specify target table ‘duplicate’ for update in FROM clause
最后我用了笨办法,复制无重复记录到新表格,删除旧表格,然后重命名新表格为旧表名称。
mysql> select * from duplicate where id in(select min(id) from duplicate group by name);
+—-+——-+
| id | name  |
+—-+——-+
|  1 | wang  |
|  3 | wdang |
|  5 | wdand |
|  6 | wddda |
+—-+——-+
4 rows in set (0.01 sec)
mysql> create table duplica select * from duplicate where id in(select min(id) from duplicate group by name);
Query OK, 4 rows affected (0.02 sec)
Records: 4  Duplicates: 0  Warnings: 0
mysql> drop table duplicate;
Query OK, 0 rows affected (0.01 sec)
mysql> alter table duplica rename to duplicate;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from duplicate;
+—-+——-+
| id | name  |
+—-+——-+
|  1 | wang  |
|  3 | wdang |
|  5 | wdand |
|  6 | wddda |
+—-+——-+
4 rows in set (0.00 sec)
mysql> alter table duplicate modify id int(2) not null primary key auto_increment;
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0
后来想了一个语句搞定了:
mysql> use mysql
Database changed
mysql> select * from duplicate;
+—-+——-+
| id | name  |
+—-+——-+
|  1 | wang  |
|  3 | wdang |
|  5 | wdand |
|  6 | wddda |
|  2 | wang  |
|  4 | wdang |
+—-+——-+
6 rows in set (0.00 sec)
mysql> delete duplicate as a from duplicate as a,
    -> (
    -> select * from duplicate group by name having count(1)>1) as b
    -> where a.name=b.name and a.id > b.id;
Query OK, 2 rows affected (0.00 sec)
mysql> select * from duplicate;
+—-+——-+
| id | name  |
+—-+——-+
|  1 | wang  |
|  3 | wdang |
|  5 | wdand |
|  6 | wddda |
+—-+——-+
4 rows in set (0.00 sec)





上一篇:做好一名DBA的基础
下一篇:Synergiser
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-3 13:22

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表