创建含有外键的表的时候遇到如下错误
ERROR 1005 (HY000): Can't create table 'eidsvr.oplog' (errno: 150)
test@3302 12:02:22>CREATE TABLE biz(
-> id INTEGER NOT NULL AUTO_INCREMENT,
-> buid VARCHAR(255),
-> appkey VARCHAR(255),
-> createtime DATETIME,
-> name VARCHAR(255),
-> seccode TEXT(2048),
-> externel1 INTEGER,
-> externel2 VARCHAR(255),
-> externel3 VARCHAR(255),
-> PRIMARY KEY (id)
-> ) ENGINE=InnoDB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8 DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.02 sec)
test@3302 12:03:13>CREATE TABLE oplog (
-> id INTEGER NOT NULL AUTO_INCREMENT,
-> eid VARCHAR(128),
-> optime DATETIME,
-> kp VARCHAR(128),
-> optype INTEGER,
-> appkey VARCHAR(255),
-> buid VARCHAR(255),
-> description VARCHAR(255),
-> externel1 INTEGER,
-> externel2 VARCHAR(255),
-> externel3 VARCHAR(255),
-> PRIMARY KEY (id),
-> FOREIGN KEY(appkey) REFERENCES biz(appkey)
-> ) ENGINE=InnoDB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8 DEFAULT CHARSET=utf8;
ERROR 1005 (HY000): Can't create table 'eidsvr.oplog' (errno: 150)
以下情况会导致上述问题
1、外键字段与要做外键校验的字段类型不匹配
2、MySQL支持外键约束,并提供与其它DB相同的功能,但表类型必须为 InnoDB,非InnoDB 存储引擎会导致报错。
3、建外键的表的那个列没有index。
针对本例,在父表上的appkey 上添加索引 解决该问题!
eidsvr@3302 12:10:09>
alter table biz add index idx_b_appkey(appkey);
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
eidsvr@3302 12:14:06>CREATE TABLE oplog (
-> id INTEGER NOT NULL AUTO_INCREMENT,
-> eid VARCHAR(128),
-> optime DATETIME,
-> kp VARCHAR(128),
-> optype INTEGER,
-> appkey VARCHAR(255),
-> buid VARCHAR(255),
-> description VARCHAR(255),
-> externel1 INTEGER,
-> externel2 VARCHAR(255),
-> externel3 VARCHAR(255),
-> PRIMARY KEY (id),
-> FOREIGN KEY(appkey) REFERENCES biz(appkey)
-> ) ENGINE=InnoDB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8 DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.00 sec)
MySQL官方提供的问题原因:
Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint.
不能在“被reference的表”即父表里找到包含“被reference字段”的索引,或者是两个关联字段类型不匹配!