ITPub博客

首页 > 数据库 > MySQL > MySQL删除表重复记录的三种方法举例

MySQL删除表重复记录的三种方法举例

原创 MySQL 作者:chenfeng 时间:2016-08-25 14:52:36 0 删除 编辑
创建实验表student表数据:
mysql> use test
Database changed
mysql> create table student (id int,name varchar(10));
Query OK, 0 rows affected (1.67 sec)

mysql> insert into student values (11,'aa');
Query OK, 1 row affected (0.26 sec)


mysql> insert into student values (12,'aa');
Query OK, 1 row affected (0.07 sec)


mysql> insert into student values (13,'aa');
Query OK, 1 row affected (0.12 sec)


mysql> insert into student values (14,'aa');
Query OK, 1 row affected (0.11 sec)


mysql> insert into student values (15,'bb');
Query OK, 1 row affected (0.19 sec)


mysql> insert into student values (16,'bb');
Query OK, 1 row affected (0.14 sec)


mysql> insert into student values (17,'cc');
Query OK, 1 row affected (0.15 sec)


mysql> select * from student;
+------+------+
| id   | name |
+------+------+
|   11 | aa   |
|   12 | aa   |
|   13 | aa   |
|   14 | aa   |
|   15 | bb   |
|   16 | bb   |
|   17 | cc   |
+------+------+
7 rows in set (0.22 sec)


方法1:
mysql>  create temporary table temp as select min(id),name from student group by name;
Query OK, 3 rows affected (0.18 sec)
Records: 3  Duplicates: 0  Warnings: 0


mysql> truncate table student;
Query OK, 0 rows affected (0.40 sec)


mysql> insert into student select * from temp;
Query OK, 3 rows affected (0.11 sec)
Records: 3  Duplicates: 0  Warnings: 0


mysql> select * from student;
+------+------+
| id   | name |
+------+------+
|   11 | aa   |
|   15 | bb   |
|   17 | cc   |
+------+------+
3 rows in set (0.00 sec)


mysql> drop temporary table temp;
Query OK, 0 rows affected (0.17 sec)


方法2:
mysql> create temporary table temp as select min(id) as MINID from student group by name;
Query OK, 3 rows affected (0.24 sec)
Records: 3  Duplicates: 0  Warnings: 0


mysql> delete from student where id not in (select minid from temp);
Query OK, 4 rows affected (0.07 sec)


mysql> select * from student;
+------+------+
| id   | name |
+------+------+
|   11 | aa   |
|   15 | bb   |
|   17 | cc   |
+------+------+
3 rows in set (0.00 sec)


方法3:
mysql> delete from student where id not in (select minid from (select min(id) as minid from student
group by name) b);
Query OK, 4 rows affected (0.19 sec)


mysql> select * from student;
+------+------+
| id   | name |
+------+------+
|   11 | aa   |
|   15 | bb   |
|   17 | cc   |
+------+------+
3 rows in set (0.00 sec)


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

请登录后发表评论 登录
全部评论
交流MySQL,PolarDB/PolarDB-X,PostgreSQL,MongoDB和Redis技术。

注册时间:2015-12-07

  • 博文量
    784
  • 访问量
    2690516