执行以下命令时:

ALTER TABLE `mytable` ADD UNIQUE (
`column1` ,
`column2`
);

我得到了这个错误信息:

#1071 - Specified key was too long; max key length is 767 bytes

columnn1和column2的信息:

column1 varchar(20) utf8_general_ci
column2  varchar(500) utf8_general_ci

我认为varchar(20)只需要21个字节,而varchar(500)只需要501个字节。所以总字节数是522,小于767。为什么我得到了错误消息?

#1071 - Specified key was too long; max key length is 767 bytes

当前回答

以下是我最初的回答:

我只是删除数据库并像这样重新创建,错误就消失了: 如果rhodes存在,则删除数据库;创建数据库rhodes default 字符集utf8默认COLLATE utf8_general_ci;

然而,它并不适用于所有情况。

这实际上是在字符集为utf8(或utf8mb4)的VARCHAR列上使用索引的问题,而VARCHAR列的字符长度超过一定长度。对于utf8mb4,这个长度是191。

有关如何在MySQL数据库中使用长索引的更多信息,请参阅本文中的长索引部分:http://hanoian.com/content/index.php/24-automate-the-converting-a-mysql-database-character-set-to-utf8mb4

其他回答

我在这个话题上做了一些搜索,最后得到了一些自定义更改

MySQL工作台6.3.7版本有图形界面

启动Workbench并选择连接。 转到管理或实例并选择选项文件。 如果Workbench要求您允许读取配置文件,然后按OK两次。 在中心位置的管理员选项文件窗口出现。 进入InnoDB选项卡,如果在General部分没有检查innodb_large_prefix。 设置innodb_default_row_format选项值为DYNAMIC。

对于6.3.7以下的版本,直接选项不可用,因此需要使用命令提示符

Start CMD as administrator. Go To director where mysql server is install Most of cases its at "C:\Program Files\MySQL\MySQL Server 5.7\bin" so command is "cd \" "cd Program Files\MySQL\MySQL Server 5.7\bin". Now Run command mysql -u userName -p databasescheema Now it asked for password of respective user. Provide password and enter into mysql prompt. We have to set some global settings enter the below commands one by one set global innodb_large_prefix=on; set global innodb_file_format=barracuda; set global innodb_file_per_table=true; Now at the last we have to alter the ROW_FORMAT of required table by default its COMPACT we have to set it to DYNAMIC. use following command alter table table_name ROW_FORMAT=DYNAMIC; Done

请检查sql_mode是否为like

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

如果是,则更改为

sql_mode=NO_ENGINE_SUBSTITUTION

OR

重新启动服务器,修改my.cnf文件(如下所示)

innodb_large_prefix=on

我认为varchar(20)只需要21个字节,而varchar(500)只需要 需要501字节。所以总字节数是522,小于767。那么,为什么 我收到错误信息了吗?

UTF8每个字符需要3个字节来存储字符串,因此在您的情况下,20 +500字符= 20*3+500*3 = 1560字节,这超过了允许的767字节。

UTF8的限制是767/3 = 255个字符,对于每个字符使用4个字节的UTF8mb4,它是767/4 = 191个字符。


如果您需要使用比限制更长的列,有两种解决方案:

Use "cheaper" encoding (the one that requires less bytes per character) In my case, I needed to add Unique index on column containing SEO string of article, as I use only [A-z0-9\-] characters for SEO, I used latin1_general_ci which uses only one byte per character and so column can have 767 bytes length. Create hash from your column and use unique index only on that The other option for me was to create another column which would store hash of SEO, this column would have UNIQUE key to ensure SEO values are unique. I would also add KEY index to original SEO column to speed up look up.

更改排序规则。您可以使用支持几乎所有功能的utf8_general_ci

这解决了我的问题

ALTER DATABASE dbname CHARACTER SET utf8 COLLATE