新手问题 新建了一个联合索引报错

xiaobai2 · 2016年10月24日 · 最后由 xiaobai2 回复于 2016年10月25日 · 2375 次阅读

我的 migration 文件如下:

class CreateNotificationSendStatistics < ActiveRecord::Migration
  def change
    create_table :notification_send_statistics do |t|
      t.integer :send_id
      t.integer :uid
      t.string :platform

      t.timestamps null: false
    end
    add_index "notification_send_statistics", ["send_id", "platform"], name: "by_send_id_and_platform", using: :btree
  end
end

Mysql2::Error: Specified key was too long; max key length is 767 bytes: CREATE INDEX by_send_id_and_platform USING btree ON notification_send_statistics (send_id, platform) 求解 搜了一下说是字符集的问题?好奇挂怎么就引起字符集问题了呢

你看看已经创建到数据库中的 notification_send_statistics 表的 platform 字段什么状态,把类型,长度,字符集都发出来看看

这是一个常见问题,InnoDB 各个列不超过 767 bytes,MyISAM 各个列不超过 1000 bytes,是受你所用的字符集是相影响的,你检查下字符集设置问题。其实也可以强制创建成功,但是会只取到前缀索引。

#2 楼 @hanluner 确实是字符集的问题

#1 楼 @huacnlee

mysql> show create table notification_send_statistics\G;
*************************** 1. row ***************************
       Table: notification_send_statistics
Create Table: CREATE TABLE `notification_send_statistics` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `send_id` int(11) DEFAULT NULL,
  `uid` int(11) DEFAULT NULL,
  `platform` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `by_send_id_and_platform` (`send_id`,`platform`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
1 row in set (0.00 sec)

把 notification_send_statistics 表的 platform 长度 limit 到 190,默认是 255。然后再试试?

@xiaobai2 应该就是字符集所导致的

#5 楼 @Kungs #6 楼 @easonlovewan #2 楼 @hanluner #1 楼 @huacnlee 问题解决了,修改字段长度或者字符集

xiaobai2 关闭了讨论。 10月25日 18:19
需要 登录 后方可回复, 如果你还没有账号请 注册新账号