ERROR 1005(HY000):无法创建表'Item_Copy'(错误号:150)无法创建表Item_Copy

时间:2014-03-24 23:28:00

标签: mysql sql

我无法创建表Item_Copy

CREATE TABLE Library
(
Library_ID int primary key,
Library_Address varchar(40),
Library_Phone bigint
);

CREATE TABLE Branch
(
Library_ID int,
Branch_Number int,
Branch_Name varchar(40),
Branch_Address varchar(40),
Branch_Phone bigint,
Branch_Hours varchar(40),
primary key (Library_ID,Branch_Number),
foreign key (Library_ID) references Library(Library_ID)
);


CREATE TABLE Item_Copy
(
Item_ID int primary key,
Copy_Number int,
Copy_Condition varchar(40),
Copy_Date_Acquired date,
Copy_Cost int,
Library_ID int,
Branch_Number int,
foreign key (Library_ID) references Branch(Library_ID),
foreign key (Branch_Number) references Branch(Branch_Number),
foreign key (Item_ID) references Item(Item_ID)
); 

2 个答案:

答案 0 :(得分:0)

只是一个科学的猜测(如果它错了会丢失)(基于Item_ID定义匹配的假设):

你想要一个复合外键,而不是两个分开的FK:

foreign key (Library_ID, Branch_Number) references Branch(Library_ID, Branch_Number)

答案 1 :(得分:0)

要定义子关系,父列必须已编制索引。

在父表Branch中,Key被定义为复合。

primary key (Library_ID,Branch_Number),

但是,在子表Item_Copy中,您试图定义独立于每列的引用键。

foreign key (Library_ID) references Branch(Library_ID),
foreign key (Branch_Number) references Branch(Branch_Number),

仅当这些字段中的每个字段都指向相应的父键时才可以接受 但是Branch(Branch_Number)没有在Branch表中定义键。因此是错误。

更改

foreign key (Library_ID) references Branch(Library_ID),
foreign key (Branch_Number) references Branch(Branch_Number),

foreign key (Library_ID, Branch_Number)
    references Branch(Library_ID, Branch_Number),