MySQL Error 150

你说的曾经没有我的故事 提交于 2019-12-08 05:31:25

Since airport_codes has multiple possible rows per airport_code and airline_code (as a composite key), it cannot be referenced by other foreign keys. Move the FK relationships into airport_codes, pointing to airport_locations and airport_codenames.

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_locations(
airport_code char(3) not null,
city varchar(20) not null,
state char(2) not null,
primary key (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)
);

INSERT INTO airport_codenames SELECT DISTINCT airline_code, name 
    FROM airport_airlines;


/* airport_codes moved after the other 2 tables, and FKs defined here */
CREATE TABLE airport_codes(
airport_code char(3) not null,
airline_code char(2) not null,
primary key (airport_code, airline_code),
/* FK relationships are defined here, rather than in the other tables,
   since the PKs for airport_code and airline_code are defined in the
   other tables.
*/
constraint ap_code_fk
    foreign key (airport_code)
    references airport_locations (airport_code),
constraint al_code_fk
    foreign key (airline_code)
    references airport_codenames (airline_code)
);

INSERT INTO airport_codes SELECT DISTINCT airport_code, airline_code 
    FROM airport_airlines;

It should come from you drop table order. Like mysql doc say

InnoDB does not permit you to drop a table that is referenced by a FOREIGN KEY constraint, unless you do SET foreign_key_checks = 0

So set the foreign key check rightfully or change your drop order in:

DROP TABLE IF EXISTS airport_locations;
DROP TABLE IF EXISTS airport_codenames;
DROP TABLE IF EXISTS airport_codes;

You drop foreign key before the reference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!