Specified key was too long; max key length is 767 bytes简单解决办法

今天做项目的时候,将本地的sql到出到服务器的mysql上错误不断,表导入成功,有两张表导入失败,报一下错误!

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

查阅资料后大概是原因

数据库表采用utf8编码,其中varchar(255)的column进行了唯一键索引

而mysql默认情况下单个列的索引不能超过767位(不同版本可能存在差异)

本人的sql语句如下

SET NAMES utf8mb4;

SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------

-- Table structure for users

-- ----------------------------

DROP TABLE IF EXISTS `users`;

CREATE TABLE `users`  (

  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,

  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,

  `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,

  `mobile` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,

  `email_verified_at` timestamp(0) NULL DEFAULT NULL,

  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,

  `remember_token` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,

  `created_at` timestamp(0) NULL DEFAULT NULL,

  `updated_at` timestamp(0) NULL DEFAULT NULL,

  PRIMARY KEY (`id`) USING BTREE,

  UNIQUE INDEX `users_email_unique`(`email`) USING BTREE

) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------

-- Records of users

-- ----------------------------

SET FOREIGN_KEY_CHECKS = 1;

分析

由于项目的用户表采用数据库迁移生成的,忘了对 `email``mobile`‘name’字段长度进行限制,用户表邮箱账号名手机号均可以用来登录服务器,均设置了唯一,mysql就会其设置索引,导致索引过长,

解决办法

1.合理分配唯一字段的长度,对 `email``mobile`‘name’字段长度减小调整为合适大小,避免浪费以及不必要的问题出现!

2  启用innodb_large_prefix选项,将约束项扩展至3072byte;(不推荐,索引过长会影响查询效率)

具体更改后的sql如下

CREATE TABLE `users` (

  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,

  `name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,

  `email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,

  `mobile` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,

  `email_verified_at` timestamp(0) NULL DEFAULT NULL,

  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,

  `remember_token` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,

  `created_at` timestamp(0) NULL DEFAULT NULL,

  `updated_at` timestamp(0) NULL DEFAULT NULL,

  PRIMARY KEY (`id`) USING BTREE,

  UNIQUE INDEX `users_email_unique`(`email`) USING BTREE

) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------

-- Records of users

-- ----------------------------

SET FOREIGN_KEY_CHECKS = 1;

你可能感兴趣的:(Specified key was too long; max key length is 767 bytes简单解决办法)