mysql删除无主键表中重复记录(只保留一条记录)

时间:2022-09-22 23:04:17

考虑多条语句变通的办法

mysql> select * from x_user;
+------+---------+-------------+
| id | name | mobile |
+------+---------+-------------+
| 1 | yangfei | 15011186301 |
| 1 | yangfei | 15011186301 |
| 1 | yangfei | 15011186301 |
| 2 | majing | 13720099441 |
| 2 | majing | 13720099441 |
| 3 | yibao | 15026418738 |
| 4 | feiy | 13886604139 |
+------+---------+-------------+
7 rows in set (0.00 sec)

一、查询出不重复的记录存入新表

mysql> create table x_user2 as (select distinct id,name,mobile from x_
user);
Query OK, 4 rows affected (0.44 sec)
Records: 4 Duplicates: 0 Warnings: 0

mysql> select * from x_user2;
+------+---------+-------------+

| id | name | mobile |
+------+---------+-------------+

| 1 | yangfei | 15011186301 |
| 2 | majing | 13720099441 |
| 3 | yibao | 15026418738 |
| 4 | feiy | 13886604139 |
+------+---------+-------------+

4 rows in set (0.00 sec)

二、删除原表中所有数据

mysql> delete from x_user;
Query OK, 7 rows affected (0.12 sec)

三、把新表中的数据写回原表

mysql> select * from x_user;
Empty set (0.00 sec)

mysql> select * from x_user2;
+------+---------+-------------+

| id | name | mobile |
+------+---------+-------------+

| 1 | yangfei | 15011186301 |
| 2 | majing | 13720099441 |
| 3 | yibao | 15026418738 |
| 4 | feiy | 13886604139 |
+------+---------+-------------+

4 rows in set (0.00 sec)

mysql> insert into x_user select * from x_user2;
Query OK, 4 rows affected (0.04 sec)
Records: 4 Duplicates: 0 Warnings: 0

mysql> select * from x_user;
+------+---------+-------------+

| id | name | mobile |
+------+---------+-------------+

| 1 | yangfei | 15011186301 |
| 2 | majing | 13720099441 |
| 3 | yibao | 15026418738 |
| 4 | feiy | 13886604139 |
+------+---------+-------------+

4 rows in set (0.00 sec)