gpt4 book ai didi

mysql - 无法创建具有两列外键约束的表?

转载 作者:行者123 更新时间:2023-11-29 11:58:31 24 4
gpt4 key购买 nike

我创建了以下机场表:

 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;

下面是当我尝试创建计划表时显示“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.

最佳答案

外键需要引用表的主(或唯一)键。没有重复项。并且,类型必须完全匹配(intint 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 Fiddle。

关于mysql - 无法创建具有两列外键约束的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32786389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com