mysql刪除重複的記錄 MYSQL刪除重覆記錄

2021-10-19 19:15:17 字數 1995 閱讀 3100

mysql刪除重覆記錄,儲存id最小的一條

方法1:

1、建立乙個臨時表,選取需要的資料。

2、清空原表。

3、臨時表資料匯入到原表。

4、刪除臨時表。

mysql> select * from student;

| id | name |

| 11 | aa |

| 12 | aa |

| 13 | bb |

| 14 | bb |

| 15 | bb |

| 16 | cc |

6 rows in set

mysql> create temporary table temp as select min(id),name from student group by name;

query ok, 3 rows affected

records: 3 duplicates: 0 warnings: 0

mysql> truncate table student;

query ok, 0 rows affected

mysql> insert into student select * from temp;

query ok, 3 rows affected

records: 3 duplicates: 0 warnings: 0

mysql> select * from student;

| id | name |

| 11 | aa |

| 13 | bb |

| 16 | cc |

3 rows in set

mysql> drop temporary table temp;

query ok, 0 rows affected

這個方法,顯然存在效率問題。

方法2:按name分組,把最小的id儲存到臨時表,刪除id不在最小id集合的記錄,如下:

mysql> create temporary table temp as select min(id) as minid from student group by name;

query ok, 3 rows affected

records: 3 duplicates: 0 warnings: 0

mysql> delete from student where id not in (select minid from temp);

query ok, 3 rows affected

mysql> select * from student;

| id | name |

| 11 | aa |

| 13 | bb |

| 16 | cc |

3 rows in set

方法3:直接在原表上操作,容易想到的sql語句如下:

mysql> delete from student where id not in (select min(id) from student group by name);

執行報錯:1093 - you can't specify target table 'student' for update in from clause

原因是:更新資料時使用了查詢,而查詢的資料又做了更新的條件,mysql不支援這種方式。

怎麼規避這個問題?

再加一層封裝,如下:

mysql> delete from student where id not in (select minid from (select min(id) as minid from student group by name) b);

query ok, 3 rows affected

mysql> select * from student;

| id | name |

| 11 | aa |

| 13 | bb |

| 16 | cc |

3 rows in set

link:

刪除MySQL表的重覆記錄

有時候遇到一些錯誤的資料庫,表中產生了一些重複的記錄,如何刪除多餘記錄就成了一件麻煩的事,今天看到乙個巧妙的解決辦法,利用了mysql的擴充套件特性,很簡單就完成了這項工作。why make this such a challenge?assuming your example create tab...

MySQL 刪除重複的記錄(簡單可行)

在網上找到的很多文章,都挺複雜而且不易理解,我自己寫了個,應該很容易理解。假設表結構為 create table orders id int 11 not null auto increment,person name varchar 12 default null,address varchar ...

刪除重複的記錄

因是手動錄入資料,所以經常會產生重複的資料,這時就需要刪除多餘的資料。建立測試用表 可以看到 allen 和 smith 這兩個人的資料重複了,現在要求表中name重複的資料只保留一行,其他的刪除。刪除資料有好幾種方法,下面介紹三種方法。方法一 通過name相同,id不同的方式來判斷。sql 如下 ...