Mysql建表的时候创建外键报错
1215 - Cannot add foreign key constraint
建表语句:
表1:
CREATE TABLE w_managers (
id int(11) AUTO_INCREMENT,
username varchar(60) NOT NULL DEFAULT '',
mobile varchar(20) NOT NULL DEFAULT '',
email varchar(60) NOT NULL DEFAULT '',
password varchar(255) NOT NULL DEFAULT '',
disabled tinyint(1) NOT NULL DEFAULT 0,
last_login int(11) NOT NULL DEFAULT 0,
created_at int(11) NOT NULL DEFAULT 0,
updated_at int(11) NOT NULL DEFAULT 0,
PRIMARY KEY(`id`),
index username_ind (`username`),
index email_ind (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;
表2:
CREATE TABLE w_auth_group (
id smallint(6) AUTO_INCREMENT,
group_name varchar(100) NOT NULL DEFAULT '',
intro varchar(255) NOT NULL DEFAULT '',
rules text,
disabled tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;
表3:
CREATE TABLE w_auth_access(
id int(11) AUTO_INCREMENT,
manager_id int(11) NOT NULL DEFAULT 0,
group_id int(11) NOT NULL DEFAULT 0,
PRIMARY KEY(`id`),
foreign key (`manager_id`) references `w_managers` (`id`) on delete cascade on update cascade,
foreign key (`group_id`) references `w_auth_group` (`id`) on delete cascade on update cascade
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;
报错:
1215 - Cannot add foreign key constraint
结果发现是外键的字段类型不一致导致的,在w_auth_group
中的id字段类型为smallint(6),在表w_auth_access
中字段类型为int(11)。
修改:
CREATE TABLE w_auth_access(
id int(11) AUTO_INCREMENT,
manager_id int(11) NOT NULL DEFAULT 0,
group_id smallint(11) NOT NULL DEFAULT 0,
PRIMARY KEY(`id`),
foreign key (`manager_id`) references `w_managers` (`id`) on delete cascade on update cascade,
foreign key (`group_id`) references `w_auth_group` (`id`) on delete cascade on update cascade
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;