2015-09-25 84 views
0

我在下面机场表创建:无法为两列创建具有外键约束的表?

CREATE TABLE airports(
    airport_id int(4) unsigned AUTO_INCREMENT NOT NULL, 
    airport_name varchar(250), 
    primary key(airport_id) 
)ENGINE=InnoDB; 

但是,当我创建进度表的外键约束,则其无法创建。以下是脚本:

CREATE TABLE schedule (
     flight_id int(3) unsigned AUTO_INCREMENT NOT NULL, 
     origin_airport_id int(4), 
     destination_airport_id int(4) , 
     departure_time char(15) not null, 
     arrival_time char(15) not null, 
     duration varchar(20) not null, 
     flight_fare decimal(9,2) not null, 
     PRIMARY KEY (flight_id), 
     FOREIGN KEY(origin_airport_id,destination_airport_id) REFERENCES airports(airport_id,airport_id) ON DELETE CASCADE ON UPDATE CASCADE 
) ENGINE=InnoDB; 

当我尝试创建计划表时,下面是来自show'engine innodb status;'的错误消息。

Error in foreign key constraint of table airport_db/schedule: 
FOREIGN KEY(origin_airport_id,destination_airport_id) REFERENCES airports(airport_id,airport_id) ON DELETE CASCADE ON UPDATE CASCADE 
) ENGINE=InnoDB: 
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.6/en/innodb-foreign- key-constraints.html for correct foreign key definition. 
+0

外键必须与引用表中的键(例如主键)相匹配!' – jarlh

+0

@jarlh:那里已经是好友了。 – Peter

+0

我的意思是FK列必须匹配数列和数据类型的PK列。 (请参阅Gordon Linoff的答案。)您需要两个独立的外键。 – jarlh

回答

1

外键需要引用表的主键(或唯一键)。没有重复。并且,类型必须完全匹配(int不匹配int unsigned)。

所以,试试这个来代替:

CREATE TABLE schedule (
     flight_id int(3) unsigned AUTO_INCREMENT NOT NULL, 
     origin_airport_id int(4) unsigned, 
     destination_airport_id int(4) unsigned, 
     departure_time char(15) not null, 
     arrival_time char(15) not null, 
     duration varchar(20) not null, 
     flight_fare decimal(9,2) not null, 
     PRIMARY KEY (flight_id), 
     FOREIGN KEY(origin_airport_id) REFERENCES airports(airport_id) ON DELETE CASCADE ON UPDATE CASCADE, 
     FOREIGN KEY(destination_airport_id) REFERENCES airports(airport_id) ON DELETE CASCADE ON UPDATE CASCADE 
) ENGINE=InnoDB; 

Here是SQL小提琴。

+0

没有工作,得到相同的错误。错误代码:1215.无法添加外键约束 – Peter

+0

非常感谢戈登。我错过了时间表中的'未签名'。非常感谢 !! – Peter