2014-11-23 32 views
1

我有表tags,我忘了在創建它時將id列設置爲主鍵。MySQL:修復完全重複的行

現在我面臨一個重複密鑰的問題。

tags表:

id  text 
1  man 
2  ball 
2  ball 
2  ball 
3  love 
3  love 
4  heart 
4  heart 

如何去除重複和保持,並設置id作爲主鍵?

預期結果:(所需的新tags表)

id  text 
1  man 
2  ball 
3  love 
4  heart 
+0

使用不同... – 2014-11-23 16:08:20

+0

我想刪除重複,(不選擇) – mwafi 2014-11-23 16:08:58

回答

1

我會做的是創建一個新表,添加密鑰插入舊錶中的數據,然後刪除tags並重命名temp

/* Make a copy of the database table (including indexes) */ 
create table tags_tmp like tags; 

/* Add the primary key to the table */ 
alter table tags_tmp add primary key (id); 

/* Insert the data from the bad table and ignore any duplicates */ 
insert ignore into tags_tmp (id, text) 
    select id, text from tags; 

/* Drop the bad table */ 
drop table tags; 

/* Rename the temporary table to the original name */ 
rename table tags_tmp to tags; 
2

我認爲最簡單的方法是創建一個臨時表的數據,然後重新加載數據:

create temporary table tags_temp as 
    select distinct id, text 
    from tags; 

truncate table tags; 

alter table tags add primary key (id); 

insert into tags(id, text) 
    select id, temp 
    from tags_temp; 
+0

我收到此錯誤:#1064 - 您的SQL語法錯誤;請檢查第1行 – mwafi 2014-11-23 16:26:05

+0

@mwafi的'add primary key(id)'附近使用的正確語法對應的MySQL服務器版本的手冊。 。 。它需要表名,oops。 – 2014-11-23 16:31:05

1

首先,我創建了表,並在插入數據:

mysql> select * from tags; 
+----+-------+ 
| id | text | 
+----+-------+ 
| 1 | man | 
| 2 | ball | 
| 2 | ball | 
| 2 | ball | 
| 3 | love | 
| 3 | love | 
| 4 | heart | 
| 4 | heart | 
+----+-------+ 
8 rows in set (0.00 sec) 

我備份不同的條目只有:

mysql> create table T as select distinct * from tags; 
Query OK, 4 rows affected (0.27 sec) 
Records: 4 Duplicates: 0 Warnings: 0 

我不再需要原來的表,所以我把它從數據庫中刪除:

mysql> drop table tags; 
Query OK, 0 rows affected (0.12 sec) 

我重新命名以前的備份表:

mysql> rename table T to tags; 
Query OK, 0 rows affected (0.08 sec) 

現在是時候主鍵約束添加到我們的表:

mysql> alter table tags add primary key(id); 
Query OK, 0 rows affected (0.48 sec) 
Records: 0 Duplicates: 0 Warnings: 0 

現在,讓我們來測試如果我們所做的是正確的。首先,讓我們來顯示數據:

mysql> select * from tags; 
+----+-------+ 
| id | text | 
+----+-------+ 
| 1 | man | 
| 2 | ball | 
| 3 | love | 
| 4 | heart | 
+----+-------+ 
4 rows in set (0.00 sec) 

讓我們試着添加一行ID = 4:

mysql> insert into tags values(4,'proof'); 
ERROR 1062 (23000): Duplicate entry '4' for key 'PRIMARY' 

結論:我們所做的事情是正確的。