MySQL 将文本列设为唯一键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14033378/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:54:57  来源:igfitidea点击:

make text column as unique key

mysqlsqldatabaseunique-key

提问by d-doctor

i want to make a table in MySQLserver with mediumtextcolumn as UNIQUE KEY

我想在MySQL服务器中制作一个表,mediumtext列为UNIQUE KEY

CREATE TABLE `parts` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` mediumtext NOT NULL,
      `display_status` int(11) NOT NULL,
       UNIQUE KEY `name` (`name`),
       PRIMARY KEY (`id`)
 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

but this made an error

但这犯了一个错误

    BLOB/TEXT column 'name' used in key specification without a key length

when I change the type of `name` to varchar .. it works!

当我将 `name` 的类型更改为 varchar 时..它起作用了!

can you tell if i can to make text column as UNIQUE KEY

你能告诉我是否可以将文本列设为 UNIQUE KEY

回答by Mari

Basically you can not use Textcolumn as UNIQUEkey. Because practically such a big column will not be unique and there might be a chance of more duplicates. So go for hashingmethod and use that output as a UNIQUE constraint.

基本上你不能使用Text列作为UNIQUE键。因为实际上如此大的列不会是唯一的,并且可能有更多重复的机会。所以转到hashing方法并将该输出用作唯一约束。

Hope this helps you

希望这对你有帮助

回答by Bohemian

The limit of 255 for varchar length no longer applies. From the documentation:

varchar 长度的 255 限制不再适用。从文档

Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions.

VARCHAR 列中的值是可变长度的字符串。在 MySQL 5.0.3 之前,长度可以指定为 0 到 255 之间的值,在 5.0.3 及更高版本中可以指定为 0 到 65,535。

Unique indexes must have a known maximum length (a requirement of mysql due to its internal implementation), so use varchar with a large enough value to fit your longest expected value, eg

唯一索引必须具有已知的最大长度(mysql 由于其内部实现而要求),因此使用具有足够大值的 varchar 以适合您最长的期望值,例如

...
`name` varchar(65535) NOT NULL, -- for example 
...