我有一个主键为varchar(255)的表。在某些情况下,255个字符是不够的。我尝试将字段更改为文本,但我得到以下错误:

BLOB/TEXT column 'message_id' used in key specification without a key length

我该如何解决这个问题?

编辑:我还应该指出,这个表有一个多列的复合主键。


当前回答

另一种很好的处理方法是创建没有唯一约束的TEXT字段,并添加一个兄弟VARCHAR字段,该字段是唯一的,并且包含TEXT字段的摘要(MD5、SHA1等)。当您插入或更新TEXT字段时,计算并存储整个TEXT字段的摘要,这样您就可以对整个TEXT字段(而不是一些前面的部分)有一个可以快速搜索的唯一性约束。

其他回答

添加另一个varChar(255)列(默认为空字符串而不是null),以在255个字符不够时保存溢出,并将此PK更改为使用两个列。然而,这听起来不像一个设计良好的数据库模式,我建议找一个数据建模师来看看你所拥有的,并对其进行重构以获得更多的规范化。

去mysql编辑表->更改列类型为varchar(45)。

DROP该表并再次运行Spring Project。 这可能会有所帮助。 有时你重写了foreignKey。

Nobody mentioned it so far... with utf8mb4 which is 4-byte and can also store emoticons (we should never more use 3-byte utf8) and we can avoid errors like Incorrect string value: \xF0\x9F\x98\... we should not use typical VARCHAR(255) but rather VARCHAR(191) because in case utf8mb4 and VARCHAR(255) same part of data are stored off-page and you can not create index for column VARCHAR(255) but for VARCHAR(191) you can. It is because the maximum indexed column size is 767 bytes for ROW_FORMAT=COMPACT or ROW_FORMAT=REDUNDANT.

For newer row formats ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED (which requires newer file format innodb_file_format=Barracuda not older Antelope) maximum indexed column size is 3072. It is available since MySQL >= 5.6.3 when innodb_large_prefix=1 (disabled by default for MySQL <= 5.7.6 and enabled by default for MySQL >= 5.7.7). So in this case we can use VARCHAR(768) for utf8mb4 (or VARCHAR(1024) for old utf8) for indexed column. Option innodb_large_prefix is deprecated since 5.7.7 because its behavior is built-in MySQL 8 (in this version is option removed).

您应该定义要索引TEXT列的哪个前导部分。

InnoDB对每个索引键有768字节的限制,你不能创建一个超过这个长度的索引。

这将很好地工作:

CREATE TABLE t_length (
      mydata TEXT NOT NULL,
      KEY ix_length_mydata (mydata(255)))
    ENGINE=InnoDB;

注意,键大小的最大值取决于列字符集。像LATIN1这样的单字节字符集有767个字符,而UTF8只有255个字符(MySQL只使用BMP,每个字符最多需要3个字节)

如果您需要整个列都是主键,计算SHA1或MD5哈希并将其用作主键。