MariaDB 不会创建以大 VARCHAR 作为 PRIMARY KEY 的表

2022-01-15 00:00:00 database mariadb mysql

我试图在 MariaDB 中创建一个表,我希望它是 VARCHAR(767) 和 PRIMARY KEY.我使用了这个命令,但这不是我想要的.

I tried to create a table in MariaDB, I wanted it to be VARCHAR(767) and PRIMARY KEY. I used this command but this is not what I want to.

CREATE TABLE main(username VARCHAR(767)  NOT NULL);

这个命令执行了,但是如果我添加PRIMARY KEY就会出现错误.

This command is executed, but if I add PRIMARY KEY the error will be appeared.

CREATE TABLE main(username VARCHAR(767) NOT NULL PRIMARY KEY);
ERROR 1071 (42000): Specified key was too long; max key length is 767 bytes

推荐答案

VARCHAR(767) 允许 767 个字符.如果默认字符集是 utf8,则需要 3*767 字节.

VARCHAR(767) allows 767 characters. If the default character set is utf8, that entails 3*767 bytes.

旧版本的索引中单个列的限制为 767 个字节.(而 PRIMARY KEY 是一个索引.)

Older versions have a limit of 767 bytes for an individual column in an index. (And PRIMARY KEY is an index.)

以下是旧版本中的 varchar 限制:

Here are the varchar limits in older versions:

  • latin1:765 个字符(长度+2 个字节;每个字符为 1 个字节)
  • utf8:255 个字符(utf8 是真实"utf8 的 3 字节子集)
  • utf8mb4:191 个字符(允许 4 字节 utf8 编码.

对于较新的版本,限制约为 4 倍.

For newer versions, the limits are about 4 times that.

如果你真的需要一个大于可用限制的 PRIMARY KEYUNIQUE KEY,我们可以讨论使用哈希等技巧.但我们需要了解什么类型的它是什么数据,你使用的是什么版本,你需要什么字符集等等.

If you really need a PRIMARY KEY or UNIQUE KEY bigger than the available limit, we can discuss tricks using hashes, etc. But we need to understand what type of data it is, what version you are using, what charset you need, etc.

相关文章