MySQL - 使现有字段唯一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5038040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL - Make an existing Field Unique
提问by Lothar
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?
如何使该字段只接受唯一值?
回答by WuHoUnited
ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);
For MySQL 5.7.4 or later:
对于 MySQL 5.7.4 或更高版本:
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.
从 MySQL 5.7.4 开始,ALTER TABLE 的 IGNORE 子句被删除,它的使用会产生错误。
So, make sure to remove duplicate entries first as IGNORE keyword is no longer supported.
因此,请确保首先删除重复条目,因为不再支持 IGNORE 关键字。
回答by Rizwan Shamsher Kaim Khani
Just write this query in your db phpmyadmin.
只需在您的 db phpmyadmin 中编写此查询即可。
ALTER TABLE TableName ADD UNIQUE (FieldName)
Eg: ALTER TABLE user ADD UNIQUE (email)
例如: ALTER TABLE user ADD UNIQUE (email)
回答by ypercube??
If you also want to name the constraint, use this:
如果您还想命名约束,请使用以下命令:
ALTER TABLE myTable
ADD CONSTRAINT constraintName
UNIQUE (columnName);
回答by Zulan
CREATE UNIQUE INDEX foo ON table_name (field_name)
CREATE UNIQUE INDEX foo ON table_name (field_name)
You have to remove duplicate values on that column before executes that sql. Any existing duplicate value on that column will lead you to mysql error 1062
在执行该 sql 之前,您必须删除该列上的重复值。该列上任何现有的重复值都会导致mysql 错误 1062
回答by MKA
The easiest and fastest way would be with phpmyadmin structure table.
最简单和最快的方法是使用 phpmyadmin 结构表。
There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.
那里是俄文,但英文版应该是一样的。只需单击唯一按钮。也可以从那里使您的列成为 PRIMARY 或 DELETE。
回答by user3772326
ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);
is the right answer
是正确答案
the insert part
插入部分
INSERT IGNORE INTO mytable ....
回答by KARTHIKEYAN.A
This code is to solve our problem to set unique key for existing table
这段代码是为了解决我们为现有表设置唯一键的问题
alter ignore table ioni_groups add unique (group_name);