Mysql去除重复记录

转自51CTO URL:http://dadloveu.blog.51cto.com/715500/196309/

有关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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值