I’m trying to create a script to normalize another table in MySQL. Below is what I have:
USE hw7;
SET foreign_key_checks = 0;
DROP TABLE IF EXISTS airport_codes;
DROP TABLE IF EXISTS airport_locations;
DROP TABLE IF EXISTS airport_codenames;
SET foreign_key_checks = 1;
CREATE TABLE airport_codes(
airport_code char(3) not null,
airline_code char(2) not null,
primary key (airport_code, airline_code)
);
INSERT INTO airport_codes SELECT DISTINCT airport_code, airline_code
FROM airport_airlines;
CREATE TABLE airport_locations(
airport_code char(3) not null,
city varchar(20) not null,
state char(2) not null,
primary key (airport_code),
constraint ap_code_fk
foreign key (airport_code)
references airport_codes(airport_code)
);
INSERT INTO airport_locations SELECT DISTINCT airport_code, city, state
FROM airport_airlines;
CREATE TABLE airport_codenames(
airline_code char(2) not null,
name varchar(20) not null,
primary key (airline_code),
constraint al_code_fk
foreign key (airline_code)
references airport_codes(airline_code)
);
INSERT INTO airport_codenames SELECT DISTINCT airline_code, name
FROM airport_airlines;
This code results in this error:
Can’t create table hw7.airport_codenames errno:150
Since
airport_codeshas multiple possible rows perairport_codeandairline_code(as a composite key), it cannot be referenced by other foreign keys. Move the FK relationships intoairport_codes, pointing toairport_locationsandairport_codenames.