简体   繁体   中英

Not able to create table with foreign key constraints for two columns?

I have created below airports table :

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

But when I'm creating schedule table with foreign key constraints,Its not able to create. Below is the script :

   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;

Below is the error message from show 'engine innodb status;', when I try to create the schedule table.

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.

Foreign keys need to reference the primary (or unique) keys of a table. There are no duplicates. And, the types have to exactly match ( int doesn't match int unsigned ).

So, try this instead:

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 is a SQL Fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM