如何为包含记录的 MySQL 中的现有 table 创建唯一索引

How to Create Unique Index for Existing table in MySQL which contains Records

在这里我想解释一下我的问题,

我需要在现有 table 中创建唯一索引,并且 table 包含很多记录。

我尝试执行这段代码

CREATE UNIQUE INDEX empid_name ON employee (importcompany_id, employee_id, name, relationship);

但出现错误

#1062 - Duplicata du champ '0-Emp ID-Member Name-Relationship' pour la clef 'empid_name' 

帮我解决这个问题,我需要使字段唯一

更新:

将这些字段设置为唯一的原因是

其实我有一个table这样的

id  company_ID  Employee_ID Name        Relationship    Dob     Age Gender       
1   EMPL        00001       Choodamani  Spouse      11-Aug-66   49  Female            
2   EMPL        00001       Komala      Mother      30-Oct-39   76  Female            
3   EMPL        00001       Varshini    Daughter    29-Apr-04   11  Female            
4   EMPL        00001       Vasudevan   Employee    15-Jul-62   53  Male    
5   EMPL        00002       Siddharth   Son         1-Jun-00    15  Male              
6   EMPL        00002       Poongavanam Mother      21-Oct-39   76  Female            
7   EMPL        00002       Aruna       Spouse      16-Sep-68   47  Female            
8   EMPL        00002       Abirami     Daughter    7-May-97    18  Female            
9   EMPL        00002       Murali      Employee    7-Oct-67    48  Male

如果插入这样的数据,

    id  company_ID  Employee_ID Name        Relationship    Dob     Age Gender       
    1   EMPL        00001       Choodamani  Spouse      11-Aug-70   45  Female            
    2   EMPL        00001       Nirmal      Son      30-Oct-39   76  Female

此插入或更新是使用 excel sheet

通过导入完成的

为此使用alter table

 ALTER TABLE `employee` ADD UNIQUE INDEX(importcompany_id, employee_id, name, relationship);

有关更多参考,请参阅 this

最简单的解决方案是添加一个名为 UniqueID 之类的新列

如果你因为任何其他原因不需要它,你可以简单地将它设置为 AutoIncrement (AI):它没有意义,但至少它是唯一的

然后更改索引,使 UniqueID 列成为 unique/primary 键。如果您想维护员工的索引,您可以这样做,但是如果您在该列中有多个记录具有相同的值,那么如果您将其指定为唯一,则会抛出错误。

  1. 如果您想要唯一索引 empid_name ON employee table 和列 (importcompany_id, employee_id, name, relationship)。那么你必须删除现有的重复数据。

执行此操作的简单方法是在 4 列上添加 UNIQUE 索引。 编写 ALTER 语句时,请包含 IGNORE 关键字 。像这样:

ALTER IGNORE TABLE `employee` ADD UNIQUE INDEX(importcompany_id, employee_id, name, relationship);

这将删除所有重复的行。作为一个额外的好处,未来重复的 INSERT 将出错。一如既往,您可能希望在 运行 类似这样的事情之前进行备份。

  1. 在您的 table 中添加主键,然后您可以轻松地从 table 中删除重复项。 然后添加唯一索引。