使用外键创建表时出现错误
create table _users(_id int(20) unsigned NOT NULL AUTO_INCREMENT,
_user_fullname varchar(50)not null,
_user_username varchar(160) not null,
_user_password varchar(200) not null,_user_remember_me tinyint,
_user_email varchar(30),
_user_mobile varchar(15),
_user_age varchar(10)
,primary key(_id,_user_email,_user_mobile));
_users 表创建成功..没有错误..
但是当我想创建员工表时:
CREATE TABLE employee ( _Id INT NOT NULL AUTO_INCREMENT,
_user_mobile VARCHAR(15) not null,
_name varchar(15),
_org varchar(10),
PRIMARY KEY (_Id),
foreign key (_user_mobile) references _users(_user_mobile));
显示错误:
ERROR 1005 (HY000): Can't create table 'DB.employee' (errno: 150)
我做错了什么?
答案 0 :(得分:2)
嘿,在这种情况下你只需要做一件事, 您只需要将索引添加到用户表的引用列,然后运行employee
的create tableALTER TABLE `_users` ADD INDEX (`_user_mobile`);
运行上面的查询后,只需运行以下查询: -
CREATE TABLE `employee`(
`_Id` INT(11) NOT NULL AUTO_INCREMENT,
`_user_mobile` VARCHAR(15) NOT NULL,
`_name` VARCHAR(15),
`_org` VARCHAR(10),
PRIMARY KEY (`_Id`),
FOREIGN KEY (`_user_mobile`) REFERENCES `_users`(`_user_mobile`) );
通过这种方式,你将摆脱mysql的错误1005,它表示你需要在父表的引用列上有索引。
答案 1 :(得分:1)
150
是外键错误:
C:\>perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
获取确切的错误消息非常棘手。您需要运行此查询:
show engine innodb status
...并在输出中搜索:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
160627 14:09:32 Error in foreign key constraint of table test/employee:
foreign key (_user_mobile) references _users(_user_mobile)):
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.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
一旦你知道这一点,就很容易添加缺失的索引:
ALTER TABLE `_users`
ADD UNIQUE INDEX `_user_email` (`_user_email`);
但如果我是你,我不会。使用手机号码作为关键是很奇怪的。相反,只需简化主键:
create table _users(_id int(20) unsigned NOT NULL AUTO_INCREMENT,
_user_fullname varchar(50)not null,
_user_username varchar(160) not null,
_user_password varchar(200) not null,_user_remember_me tinyint,
_user_email varchar(30),
_user_mobile varchar(15),
_user_age varchar(10)
,primary key(_id));
...并在链接表中使用:
CREATE TABLE employee ( _Id INT NOT NULL AUTO_INCREMENT,
_user_id int(20) unsigned not null,
_name varchar(15),
_org varchar(10),
PRIMARY KEY (_Id),
foreign key (_user_id) references _users(_id));
答案 2 :(得分:0)
问题出在外键部分。如果删除它,将创建表没有问题。
如果需要使用该外键,则需要使用InnoDB作为MySQL的存储引擎。 InnoDB允许外键约束引用非唯一键,如here中所示。