简体   繁体   English

在现有 MySQL 表中添加具有唯一键索引的新字段

[英]Adding new field with Unique key index in existing MySQL table

I am trying to add a column with Unique Key (so it will not have duplicate records) in existing MySQL table that contains multiple rows of data.我正在尝试在包含多行数据的现有 MySQL 表中添加具有唯一键的列(因此它不会有重复的记录)。

ALTER TABLE  `common`.`fraud_payment_log`
  ADD  `retainer_id` VARCHAR( 20 ) NOT NULL,
  ADD  `http_referrer` VARCHAR( 255 ) NULL ,
  ADD UNIQUE (`retainer_id`);

But it is throwing below error:但它抛出以下错误:

ERROR 1062 (23000): Duplicate entry '' for key 'retainer_id'

The error is because of the duplicate empty value which will come when we adding a new column in the existing table with records.错误是因为当我们在现有表中添加一个带有记录的新列时会出现重复的空值。

Can anyone please suggest how to achieve this?任何人都可以请建议如何实现这一目标?

You cannot add a unique, non-NULL column to a table that has more than one row.不能向具有多行的表添加唯一的非 NULL 列。 By definition, two rows would get the same value.根据定义,两行将获得相同的值。

Add the columns first, allowing NULL values:首先添加列,允许 NULL 值:

ALTER TABLE  `common`.`fraud_payment_log`
    ADD  `retainer_id` VARCHAR( 20 ) NULL,
    ADD  `http_referrer` VARCHAR( 255 ) NULL;

Now, populate the column so it has different values.现在,填充该列,使其具有不同的值。 Say:说:

update `common`.`fraud_payment_log` cross join
       (select @rn := 0) vars
     set retainer_id = (@rn := @rn + 1);

Then add the unique constraint.然后添加唯一约束。 I usually do this with the index directly:我通常直接用索引来做这个:

create unique index idx_fpl_retainer on  `common`.`fraud_payment_log`(retainer_id);

If the table is empty, then just recreate the table with all the columns you want.如果表为空,则只需重新创建包含您想要的所有列的表。

Follow this steps:请按照以下步骤操作:

  • Add new field which is not unique添加不唯一的新字段
  • Update table and put unique values in that field更新表并在该字段中放置唯一值
  • Alter table to make this field as unique更改表以使此字段唯一

您应该首先添加列,然后用唯一值填充它,然后添加UNIQUE约束。

You should specify a DEFAULT NULL ;您应该指定一个DEFAULT NULL NULL doesn't count against UNIQUE checks, so your table will be first filled with NULL values, then you'll proceed to fill it as you wish. NULL 不计入 UNIQUE 检查,因此您的表将首先填充 NULL 值,然后您将根据需要继续填充它。

  1. Create new column using UI or query(My new column is sensorID )使用 UI 或查询创建新列(我的新列是sensorID
  2. Fire this :火这个:

UPDATE client set sensorID=id更新客户端设置sensorID=id

  1. In above query client is my table , sensorID is my newly added column on which I wanted to apply unique, id is my primary key type column in existing table.在上面的查询客户端是我的表, sensorID是我想要应用唯一的新添加的列, id是我现有表中的主键类型列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM