mysql重複資料刪除記錄,儲存Id最小的一條

來源:互聯網
上載者:User

標籤:

方法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 setmysql> create temporary table temp as select min(id),name from student group by name;Query OK, 3 rows affectedRecords: 3 Duplicates: 0 Warnings: 0mysql> truncate table student;Query OK, 0 rows affectedmysql> insert into student select * from temp;Query OK, 3 rows affectedRecords: 3 Duplicates: 0 Warnings: 0mysql> select * from student;+----+------+| ID | NAME |+----+------+| 11 | aa || 13 | bb || 16 | cc |+----+------+3 rows in setmysql> 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 affectedRecords: 3 Duplicates: 0 Warnings: 0mysql> delete from student where id not in (select minid from temp);Query OK, 3 rows affectedmysql> 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 affectedmysql> select * from student;+----+------+| ID | NAME |+----+------+| 11 | aa || 13 | bb || 16 | cc |+----+------+3 rows in sethttp://www.cnblogs.com/nzbbody/p/4470638.html

mysql重複資料刪除記錄,儲存Id最小的一條

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.