2014-11-23 50 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' 

结论:我们所做的事情是正确的。