• django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes');


    在使用utf8mb4字符集的情况下,如果列存在索引,那么varchar的最大长度是191

    数据库版本:

     在使用utf8字符集的情况下,如果列存在索引,那么varchar的最大长度是255。

    在大字段上创建索引时,有时会碰到下面的错误

    ERROR 1709 (HY000): Index column size too large. The maximum column size is 767 bytes.

    1. 错误原因

    由于 MySQL Innodb 引擎表索引字段长度的限制为 767 字节,因此对于多字节字符集的大字段(或者多字段组合索引),创建索引会出现上面的错误。

    以 utf8mb4 字符集 字符串类型字段为例:utf8mb4 是 4 字节字符集,则默认支持的索引字段最大长度是: 767 字节 / 4 字节每字符 = 191 字符,因此在 varchar(255) 或 char(255) 类型字段上创建索引会失败。

    注:MySQL官网关于 utf8mb4 字符集的参考文档

    2. 解决步骤

    Step 1. RDS 控制台  参数设置,调整参数 innodb_large_prefix 为 ON

    将 Innodb_large_prefix 修改为 on 后,对于 Dynamic 和 Compressed 格式的InnoDB 引擎表,其最大的索引字段长度支持到 3072 字节。

    Step 2. 创建表的时候指定表的 row format 格式为 Dynamic 或者 Compressed,如下示例:

    create table idx_length_test_02
    (
      id int auto_increment primary key,
      name varchar(255)
    ) 
    ROW_FORMAT=DYNAMIC default charset utf8mb4;

      

     insert into idx_length_test_02 values (null,'xxxxxxxxxx');

     create index idx_name on idx_length_test_02 (name);

    show warnings;
    show create table idx_length_test_02 G

    Step 3. 修改现有表

    对已经创建的表,通过下面的语句修改下表的 row_format 格式

    alter table <table_name> row_format=dynamic;
    alter table <table_name> row_format=compressed;

    使用python的依赖:django-guardian(作用是实现精细的权限控制),也发生了错误:Specified key was too long,max key length is 767 bytes,原因是这个插件需要创建数据表,而表里有索引,而使用所有的字段长度为255,超过了限制:

    参考:https://github.com/celery/django-celery-beat/issues/18

    这篇文章https://help.aliyun.com/knowledge_detail/41707.html描述的比较清楚

  • 相关阅读:
    webstrom破解的问题
    redis高级应用(1)
    linux之软链接、硬链接
    爬虫之scrapy、scrapy-redis
    爬虫之xpath、selenuim
    爬虫之Beautifulsoup模块
    爬虫之Reuqests模块使用
    测试项目配置
    Cleary基础
    Redis基础
  • 原文地址:https://www.cnblogs.com/shengulong/p/10105128.html
Copyright © 2020-2023  润新知