执行以下命令时:
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
关于为什么你会得到错误消息的答案已经被很多用户回答了。我的答案是如何修复和使用它。
从这个链接中查阅。
打开MySQL客户端(或MariaDB客户端)。它是一个命令行工具。
它会问你的密码,输入正确的密码。
使用以下命令选择您的数据库:
数据库修改
设置全局innodb_large_prefix=on;
查询OK, 0行受影响(0.00秒)
set global innodb_file_format=Barracuda;
查询OK, 0行受影响(0.02秒)
去phpMyAdmin或类似的数据库,以便于管理。>选择数据库>查看表结构>进入“操作”页签。>将ROW_FORMAT更改为DYNAMIC并保存更改。
进入表的结构选项卡>单击唯一按钮。
完成了。现在应该没有错误了。
这个修复的问题是,如果你导出数据库到另一个服务器(例如从本地主机到真实主机),你不能在该服务器上使用MySQL命令行。你不能让它在那里工作。
Laravel框架解决方案
根据Laravel 5.4。*文档;你必须在app/Providers/AppServiceProvider.php文件的引导方法中设置默认字符串长度,如下所示:
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
Laravel 5.4对这个修复的解释。*文档:
Laravel uses the utf8mb4 character set by default, which includes support for storing "emojis" in the database. If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure this by calling the Schema::defaultStringLength method within your AppServiceProvider.
Alternatively, you may enable the innodb_large_prefix option for your
database. Refer to your database's documentation for instructions on
how to properly enable this option.
Specified key was too long; max key length is 767 bytes
You got that message because 1 byte equals 1 character only if you use the latin-1 character set. If you use utf8, each character will be considered 3 bytes when defining your key column. If you use utf8mb4, each character will be considered to be 4 bytes when defining your key column. Thus, you need to multiply your key field's character limit by, 1, 3, or 4 (in my example) to determine the number of bytes the key field is trying to allow. If you are using uft8mb4, you can only define 191 characters for a native, InnoDB, primary key field. Just don't breach 767 bytes.
我发现这个查询在检测哪些列的索引违反了最大长度方面很有用:
SELECT
c.TABLE_NAME As TableName,
c.COLUMN_NAME AS ColumnName,
c.DATA_TYPE AS DataType,
c.CHARACTER_MAXIMUM_LENGTH AS ColumnLength,
s.INDEX_NAME AS IndexName
FROM information_schema.COLUMNS AS c
INNER JOIN information_schema.statistics AS s
ON s.table_name = c.TABLE_NAME
AND s.COLUMN_NAME = c.COLUMN_NAME
WHERE c.TABLE_SCHEMA = DATABASE()
AND c.CHARACTER_MAXIMUM_LENGTH > 191
AND c.DATA_TYPE IN ('char', 'varchar', 'text')