MySQL - 使现有字段唯一

2021-11-20 00:00:00 mysql unique-constraint

我有一个已经存在的表,其中的字段应该是唯一的,但不是.我只知道这一点,因为表中的一个条目与另一个已经存在的条目具有相同的值,这导致了问题.

如何让这个字段只接受唯一值?

解决方案

ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);

<小时>

对于 MySQL 5.7.4 或更高版本:

ALTER TABLE mytbl ADD UNIQUE (columnName);

<块引用>

从 MySQL 5.7.4 开始,ALTER TABLE 的 IGNORE 子句被删除,并且它的使用会产生错误.

因此,请务必先删除重复条目,因为不再支持 IGNORE 关键字.

参考

I have an already existing table with a field that should be unique but is not. I only know this because an entry was made into the table that had the same value as another, already existing, entry and this caused problems.

How do I make this field only accept unique values?

解决方案

ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);


For MySQL 5.7.4 or later:

ALTER TABLE mytbl ADD UNIQUE (columnName);

As of MySQL 5.7.4, the IGNORE clause for ALTER TABLE is removed and its use produces an error.

So, make sure to remove duplicate entries first as IGNORE keyword is no longer supported.

Reference

相关文章