代码之家  ›  专栏  ›  技术社区  ›  Elie

外键和MySQL错误

  •  10
  • Elie  · 技术社区  · 15 年前

    我使用下面的脚本在MySQL版本5.1中创建一个表,它将引用其他3个表。所有3个表都是使用InnoDB创建的,所有3个表的ID列都定义为INT。

    失败的脚本是(为了简单起见,删除了额外的列):

    CREATE TABLE WORK_ORDER (
        ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        ACCOUNT_ID INT NOT NULL,
        CUSTOMER_ID INT NOT NULL,
        SALES_ID INT,
        TRADES_ID INT,
        LOCATION_ID INT NOT NULL,
        INDEX CUST_INDEX(CUSTOMER_ID),
        INDEX SALES_INDEX(SALES_ID),
        INDEX TRADES_INDEX(TRADES_ID),
        INDEX ACCOUNT_INDEX(ACCOUNT_ID),
        INDEX LOCATION_INDEX(LOCATION_ID),
        FOREIGN KEY (CUSTOMER_ID) REFERENCES PERSON(ID) ON DELETE CASCADE,
        FOREIGN KEY (SALES_ID) REFERENCES PERSON(ID) ON DELETE SET NULL,
        FOREIGN KEY (TRADES_ID) REFERENCES PERSON(ID) ON DELETE SET NULL,
        FOREIGN KEY (ACCOUNT_ID) REFERENCES ACCOUNT(ID) ON DELETE CASCADE,
        FOREIGN KEY (LOCATION_ID) REFERENCES ADDRESS(ID) ON DELETE SET NULL
    ) ENGINE=InnoDB;
    

    CREATE TABLE ADDRESS (
        ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        PERSON_ID INT NOT NULL,
        ACCOUNT_ID INT NOT NULL,
        ADDRESS_L1 VARCHAR(50),
        ADDRESS_L2 VARCHAR(50),
        CITY VARCHAR(25),
        PROVINCE VARCHAR(20),
        POSTAL_CODE VARCHAR(6),
        COUNTRY VARCHAR(25),
        INDEX CUST_INDEX(PERSON_ID),
        INDEX ACCOUNT_INDEX(ACCOUNT_ID),
        FOREIGN KEY (ACCOUNT_ID) REFERENCES ACCOUNT(ID) ON DELETE CASCADE,
        FOREIGN KEY (PERSON_ID) REFERENCES PERSON(ID) ON DELETE CASCADE
    ) ENGINE=InnoDB;
    

    我在这里浏览了几个关于类似问题的问题,但大多数问题似乎是重复的定义和不匹配的字段类型,还有一些表没有使用InnoDB。然而,这些似乎都不是问题所在。有什么想法吗?

    1 回复  |  直到 13 年前
        1
  •  18
  •   Marc B    11 年前

    您始终可以发出“SHOW ENGINE INNODB STATUS”命令。输出中将隐藏一个“最新外键错误”部分,该部分将详细介绍导致“150”错误的确切原因:

    mysql> create table a (x int not null) type=innodb;
    Query OK, 0 rows affected, 1 warning (0.02 sec)
    
    mysql> create table b (y int not null, foreign key (y) references a (x) on delete set null) type=innodb;
    ERROR 1005 (HY000): Can't create table './test/b.frm' (errno: 150)
    
    mysql> show engine innodb status;
    [..... snip snip snip ...]
    ------------------------
    LATEST FOREIGN KEY ERROR
    ------------------------
    091129 16:32:41 Error in foreign key constraint of table test/b:
    foreign key (y) references a (x) on delete set null) type=innodb:
    You have defined a SET NULL condition though some of the
    columns are defined as NOT NULL.
    [.... snip snip snip ...]
    
    推荐文章