MySQL 1005错误

时间:2013-07-03 12:44:10

标签: mysql mysql-error-1005

我正在为我的在线投资组合网站编写一个MySQL数据库来编制我为客户/项目所做的所有设计/工作,我这样做是为了使添加新作品更容易而不必编辑手动标记。

无论如何,我尝试运行以下脚本:

create table album (
   AlbumID int not null,
   AlbumOrder int not null,
   AlbumName varchar(100),
   primary key (AlbumID, AlbumOrder)
);

create table category (
   CategoryID int not null primary key auto_increment,
   CategoryName varchar(100)
);

create table item (
   ItemID int not null primary key auto_increment,
   CategoryID int not null,
   AlbumID int not null,
   AlbumOrder int not null,
   ItemName varchar(100),
   Description varchar(500),
   ThumbPath varchar(100),
   PhotoPath varchar(100),
   InsertDate datetime,
   EditDate datetime,
   constraint fk_catID foreign key (CategoryID) references category (CategoryID) on update cascade,
   constraint fk_albID foreign key (AlbumID) references album (AlbumID) on update cascade,
   constraint fk_albOrd foreign key (AlbumOrder) references album (AlbumOrder) on update cascade
);

我收到1005错误,说无法创建项目表。我不知道问题出在哪里,但我确信这很明显!

编辑:使用的引擎是innoDB。

3 个答案:

答案 0 :(得分:0)

看起来你的相册可能会导致问题。你应该有一个基于2列的FK,而不是每个基于1列的2个FK,就像这样(删除fk_albOrd行):

constraint fk_albID foreign key (AlbumID,AlbumOrder) references album (AlbumID,AlbumOrder) on update cascade

此脚本在SQL Fiddle中创建表格时没有错误:

create table album (
   AlbumID int not null,
   AlbumOrder int not null,
   AlbumName varchar(100),
   primary key (AlbumID, AlbumOrder)
);

create table category (
   CategoryID int not null primary key auto_increment,
   CategoryName varchar(100)
);

create table item (
   ItemID int not null primary key auto_increment,
   CategoryID int not null,
   AlbumID int not null,
   AlbumOrder int not null,
   ItemName varchar(100),
   Description varchar(500),
   ThumbPath varchar(100),
   PhotoPath varchar(100),
   InsertDate datetime,
   EditDate datetime,
   constraint fk_catID foreign key (CategoryID) references category (CategoryID) on update cascade,
   constraint fk_albID foreign key (AlbumID,AlbumOrder) references album (AlbumID,AlbumOrder) on update cascade

);

答案 1 :(得分:0)

您的陈述现在没有任何问题。

我刚刚在我的测试mysql环境中成功执行了它们。但是,我的环境可能与您的环境不同:我的默认引擎是InnoDB,您的环境可能不同。

由于您使用的是外键约束,因此应明确指定引擎是InnoDB(“...)engine = Innodb”。

也可能是因为您已经存在一个或多个表。在每个创建之前使用DROP ...如果EXISTS它应该可以正常工作。

答案 2 :(得分:0)

通过在收到错误后立即运行MySQL语句show engine innodb status,您可以检索有关错误的更多详细信息(缩短输出):

LATEST FOREIGN KEY ERROR

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.

在引用的表中,必须有一个索引,其中引用的列被列为第一列。这对fk_albOrd foreign key (AlbumOrder)无效。

要解决此问题,您可以为AlbumOrder表格中的列Album添加索引,或者 - 最好 - 删除fk_albOrd并更改fk_albID根据Derek Kromm的建议约束一组列:

constraint fk_albID foreign key (AlbumID, AlbumOrder) references album (AlbumID, AlbumOrder) on update cascade