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

报错

Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email))

原因

As you can see in the error message - "The maximum column size is 767 bytes", if you want to create an index on it. A VARCHAR(255) column can take up to 765 (2553) bytes using utf8 and 1020 (2554) bytes using utf8mb4. This is because in MySQL utf8 takes up to 3 bytes and utf8mb4 up to 4 bytes (the real UTF8). Thus creating a VARCHAR(255) (unique) index with utf8mb4 will fail.

解决办法

以下三种方式都是可以的:

  • MySQL 5.7 avoids the problem. Consider upgrading.
  • VARCHAR(255) is usually var bigger than necessary. If you can safely shrink to 191 or less, the error will go away.
  • Switch to utf8 (from utf8mb4), if you don't need Chinese or Emoji.
添加新评论