• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

MYSQL剔除重复记录(此处有正解)

mysql 搞代码 7年前 (2018-06-05) 123次浏览 已收录 0个评论

mysql删除重复记录(此处有正解)

有关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)
文章出处:飞诺网(www.firnow.com):http://dev.firnow.com/course/7_databases/mysql/Mysqljs/20100710/399218.html


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:MYSQL剔除重复记录(此处有正解)
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址