刪除MySQL表的重複記錄

來源:互聯網
上載者:User

有時候遇到一些錯誤的資料庫,表中產生了一些重複的記錄,如何刪除多餘記錄就成了一件麻煩的事,今天看到一個巧妙的解決辦法,利用了MySQL的擴充特性,很簡單就完成了這項工作。

 

Why make this such a challenge?

Assuming your example:
CREATE TABLE bad_table2 (
id INT NOT NULL UNIQUE AUTO_INCREMENT,
name VARCHAR(20) NOT NULL
);

INSERT INTO bad_table2(id,name) VALUES
(1,'Things Fall Apart'),
(2,'Things Fall Apart'),
(3,'The Famished Road'),
(4,'Things Fall Apart'),
(5,'The Famished Road'),
(6,'Thirteen cents'),
(7,'Thirteen cents');

I can remove duplicates easily with the following line:
alter ignore table bad_table2 add unique index `unique_index` (name);

And then remove the added index.
alter table bad_table2 drop index `unique_index`;

Viola, dups gone.

 

這裡有兩個關鍵點,唯一索引和ignore關鍵字,MySQL對ignore的解釋如下:

 

IGNORE是MySQL相對於標準SQL的擴充。如果在新表中有重複關鍵字,或者當STRICT模式啟動後出現警告,則使用IGNORE控制ALTER
TABLE的運行。如果沒有指定IGNORE,當重複關鍵字錯誤發生時,複製操作被放棄,返回前一步驟。如果指定了IGNORE,則對於有重複關鍵字的行,只使用第一行,其它有衝突的行被刪除。並且,對錯誤值進行修正,使之盡量接近正確值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.