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

2021-09-08 18:55:29 字數 2206 閱讀 3293

方法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

刪除重覆記錄

我們經常在資料庫中有重複的記錄這時候我們希望刪除那些重複的記錄 你不要告訴我你是一條條手動刪除的哈 select distinct into newtable form 程式設計客棧nbsp tablename drop table tabwww.cppcns.comlename select in...

SQL查詢重覆記錄,刪除重覆記錄

1 查詢表中多餘的重覆記錄,重覆記錄是根據單個字段 docid 來判斷 select from tablename where docid in select docid from tablename group by docid h ing count docid 1 例二 select from...

刪除MySQL表的重覆記錄

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