MySQL错误150

时间:2012-03-26 02:43:11

标签: mysql sql mysql-error-1005

我正在尝试创建一个脚本来规范化MySQL中的另一个表。以下是我的内容:

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;

此代码导致此错误:

  

无法创建表hw7.airport_codenames错误:150

2 个答案:

答案 0 :(得分:1)

由于airport_codes每个airport_codeairline_code有多个可能的行(作为复合键),因此其他外键不能引用它。将FK关系移至airport_codes,指向airport_locationsairport_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;

答案 1 :(得分:0)

它应该来自你下拉表顺序。就像mysql doc说的那样

  

InnoDB不允许您删除由FOREIGN KEY约束引用的表,除非您执行SET foreign_key_checks = 0

因此,正确设置外键检查或更改下拉顺序:

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

在引用之前删除外键。