2011-08-26 82 views
2

我在我的MySql服務器中有一個表,其列如下: ID(int,key),type(int),name(varchar)。MySql - 從表中刪除重複

由於我的應用程序出現錯誤,重複的條目被插入到數據庫中,我想刪除這些條目,所以從每個類型&名稱對只會有一行。

有關如何做到這一點的任何想法?

+0

可能重複[什麼是重複數據表的最佳方式?](http://stackoverflow.com/questions/2230295/whats-the-best-way-to-dedupe-a-table) –

回答

0

顯然,這首先查詢更改爲select語句,以確保被選中要刪除的正確記錄:

delete from table as t1 
using table as t2 
where t1.type = t2.type and t1.name = t2.name and t1.id > t2.id 
+0

有趣的語法, '刪除..使用'。我想這是MySQL特有的? –

+0

是的,請參閱文檔:http://dev.mysql.com/doc/refman/5.0/en/delete.html –

+0

我試着運行腳本:'從s_relations中刪除爲t1 使用s_relations作爲t2 其中t2.source_persona_id = t1.source_persona_id 和t2.relation_type = t1.relation_type 和t2.message_id = t1.message_id 和t2.target_object_id = t1.target_object_id 和t1.id> t2.id',但得到了以下錯誤:'SQL錯誤:您的SQL語法有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在't1 t1 使用s_relations作爲t2'時使用正確的語法'其中t2.source_persona_id =第1行't1.source_persona_i' – Ran

1

這取決於你想保留什麼,你要刪除的內容。由於ID是一個關鍵,我猜測沒有重複的ID,但重複的類型/名稱對。因此,這裏有一個關於如何刪除它們的想法:

delete from my_table t1 
where exists (select 1 
       from my_table t2 
       where t2.type = t1.type 
       and t2.name = t1.name 
       and t2.id < t1.id) 

這將保持「重複」用最低的ID

    and t2.id > t1.id 

這將保持「重複」具有最高ID

+0

您的條件方向相同兩次,兩者都會保存最低的「id」。 –

+0

哎呀,謝謝! –

+0

我試圖運行以下:'從s_relations T1 其中存在刪除(從s_relations T2 選擇1 其中t2.source_persona_id = t1.source_persona_id 和t2.relation_type = t1.relation_type 和t2.message_id = t1時。 message_id 和t2.target_object_id = t1.target_object_id 和t1.id> t2。ID)',但得到了以下錯誤:'SQL錯誤:你在你的SQL語法錯誤;檢查對應於你的MySQL服務器版本使用附近的正確語法手冊在行「T1 其中存在的(從s_relations T2 選擇1 」 1' – Ran

0

您需要選擇不同的新表格,然後刪除舊錶格並重命名新表格。但也有很多方法來完成這件事:

What's the best way to dedupe a table?

+0

尼斯的鏈接,這些都是一些有趣的技術 –