执行以下命令时:

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

当前回答

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

其他回答

如果你要创建如下内容:

CREATE TABLE IF NOT EXISTS your_table (
  id int(7) UNSIGNED NOT NULL AUTO_INCREMENT,
  name varchar(256) COLLATE utf8mb4_bin NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY name (name)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ROW_FORMAT=FIXED;

应该是这样的

CREATE TABLE IF NOT EXISTS your_table (
      id int(7) UNSIGNED NOT NULL AUTO_INCREMENT,
      name varchar(256) COLLATE utf8mb4_bin NOT NULL,
      PRIMARY KEY (id)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ROW_FORMAT=FIXED;

但是您需要从代码中检查该列的唯一性,或者添加一个新列作为varchar列的MD5或SHA1

我解决了这个问题:

varchar(200) 

取而代之的是

varchar(191)

所有超过200的唯一或主varchar键将它们替换为191或将它们设置为文本。

在导入文件中用utf8替换utf8mb4。

但请注意,utf8字符集已弃用,它不支持所有的Unicode字符,例如表情符号,所以如果这样做,您将失去对Unicode的完全支持。

好吧,在我的情况下,我必须将数据库文件从mySQL 5.7恢复到mySQL 5.6,我遇到了这个问题。

根本原因是版本不兼容,并且索引的某些列长于191(默认值为255)。

所以解决方案很简单:让所有“索引列的长度”都小于191(例如180)

我认为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.