我在MySQL命令行中运行了以下查询,并创建了表。但当我在XAMPP中运行时,我收到错误“1005 - 无法创建表'zoneboard.work'(错误号:150)”
我的查询是:
Create Table user (
id_user INT (50)NOT NULL AUTO_INCREMENT ,
email VARCHAR( 64 ) NOT NULL ,
username VARCHAR( 16 ) NOT NULL ,
password VARCHAR( 32 ) NOT NULL ,
PRIMARY KEY ( id_user )
) ENGINE = InnoDB
CREATE TABLE work (
id_user INT( 50 ) NOT NULL AUTO_INCREMENT ,
task VARCHAR( 50 ) NOT NULL ,
comments VARCHAR( 100 ) NOT NULL ,
assignee VARCHAR( 16 ) NOT NULL ,
priority VARCHAR( 50 ) NOT NULL ,
status VARCHAR( 50 ) NOT NULL ,
dataum1 VARCHAR( 50 ) NOT NULL ,
dataum2 VARCHAR( 50 ) NOT NULL ,
PRIMARY KEY ( id_user ),
FOREIGN KEY(assignee) REFERENCES user(username)
) ENGINE = InnoDB
答案 0 :(得分:1)
根据MySQL文档:If you are creating a table, it must have the right column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns error number 1005 and refers to error 150 in the error message.
因此,请尝试在外键字段username
上添加索引,如下所示:
CREATE INDEX username_index ON 'user'(username)
答案 1 :(得分:1)
您应该参考用户表的主键。整数更快,使用主键而不是非唯一值更安全。想象一下,你有2行或更多行具有相同的用户名。
CREATE TABLE `work` (
`id_user` int(50) NOT NULL AUTO_INCREMENT,
`task` varchar(50) NOT NULL,
`comments` varchar(100) NOT NULL,
`assignee` int(50) NOT NULL,
`priority` varchar(50) NOT NULL,
`status` varchar(50) NOT NULL,
`dataum1` varchar(50) NOT NULL,
`dataum2` varchar(50) NOT NULL,
PRIMARY KEY (`id_user`),
KEY `assignee` (`assignee`),
CONSTRAINT `assignee` FOREIGN KEY (`assignee`) REFERENCES `user` (`id_user`)
) ENGINE=InnoDB;
答案 2 :(得分:0)
CREATE TABLE USER (
id_user INT (50)NOT NULL AUTO_INCREMENT ,
email VARCHAR( 64 ) NOT NULL ,
username VARCHAR( 16 ) NOT NULL ,
PASSWORD VARCHAR( 32 ) NOT NULL ,
PRIMARY KEY ( id_user, username ),
INDEX(username)
) ENGINE = INNODB;
父表用户应该有一个索引列(这里应该对用户名进行索引)。 请参阅:http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
InnoDB允许外键引用任何索引列或列组。但是,在引用的表中,必须有一个索引,其中引用的列被列为相同顺序的第一列。