添加多个外键会出错

时间:2016-04-06 07:35:30

标签: mysql foreign-keys

我正在尝试在表'routes1'上添加多个外键但它仍然给我一个错误Cannot add foreign key constraint,我错过了一些代码吗? 提前致谢。 这是代码片段

CREATE TABLE `routes1` (
  `Airline` varchar(3) default NULL,
  `Airline_ID` int(11) default NULL,
  `Source_Airport` varchar(4) default NULL,
  `Source_Airport_ID` varchar(5) default NULL,
  `Destination_Airport` varchar(4) default NULL,
  `Destination_Airport_ID` varchar(4) default NULL,
  `CodeShare` char(1),
  `Stops` int(1),
  `Equipment` text,
 FOREIGN KEY(Airline_ID) REFERENCES airlines(Airline_ID)
  ON DELETE CASCADE ON UPDATE CASCADE,
 FOREIGN KEY(Source_Airport_ID) REFERENCES airports(Airport_ID)
  ON DELETE CASCADE ON UPDATE CASCADE
 );

以下是“airport”引用表

的创建表脚本
CREATE TABLE `airports` (
  `Airport_ID` int(5),
  `Name` text,
  `City` text,
  `Country` text,
  `IATA/FAA`text default NULL,
 `ICAO` text,
  `Latitude` double NOT NULL,
  `Longitude` double NOT NULL,
  `Altitude` double NOT NULL,
  `Timezone` double not null,
 `dst` char(1) default NULL,
 `Tz_Database_time_zone` text,
  PRIMARY KEY  (`Airport_ID`)
  );

1 个答案:

答案 0 :(得分:5)

请查看Airline_ID和Source_Airport_ID数据类型的更改:数据类型应与外键的源表相同。

CREATE TABLE `routes1` (
`Airline` varchar(3) default NULL,
`Airline_ID` int(5) default NULL,
`Source_Airport` varchar(4) default NULL,
`Source_Airport_ID` int(5) default NULL,
`Destination_Airport` varchar(4) default NULL,
`Destination_Airport_ID` varchar(4) default NULL,
`CodeShare` char(1),
`Stops` int(1),
`Equipment` text,
 FOREIGN KEY(Airline_ID) REFERENCES airlines(Airline_ID)
 ON DELETE CASCADE ON UPDATE CASCADE,
 FOREIGN KEY(Source_Airport_ID) REFERENCES airports(Airport_ID)
 ON DELETE CASCADE ON UPDATE CASCADE
);

如果答案是正确的,请标记为答案。谢谢。

有关详细信息,请参阅以下链接:

  

Supports transactions, row-level locking, and foreign keys