MYSQL外键错误:150无法创建表

时间:2013-09-26 05:30:00

标签: mysql sql foreign-keys foreign-key-relationship

我一直在阅读有关此问题的StackOverflow和各种论坛,但我似乎无法弄明白。当尝试运行下面的“CREATE TABLE类”和“CREATE TABLE Enroll”命令时,我得到“ERROR 1005:无法创建table university.class(errno:150)”。我使用InnoDB作为我的存储引擎。前两个“CREATE”语句工作正常。

我需要做哪些更改才能使“CREATE TABLE类和CREATE TABLE Enroll”部分工作?

CREATE TABLE Student (
    stuId VARCHAR(6),
    lastName VARCHAR(20) NOT NULL,
    firstName VARCHAR(20) NOT NULL,
    major VARCHAR(10),
    credits FLOAT(3) DEFAULT 0,
    CONSTRAINT Student_stuId_pk PRIMARY KEY (stuId),
    CONSTRAINT Student_credits_cc CHECK ((credits>=0) AND (credits < 150)));

CREATE TABLE Faculty (
    facId VARCHAR(6),
    name VARCHAR(20) NOT NULL,
    department VARCHAR(20),
    rank VARCHAR(10),
    CONSTRAINT Faculty_facId_pk PRIMARY KEY (facId));

CREATE TABLE Class (
    classNumber VARCHAR(8),
    facId VARCHAR(6) NOT NULL,
    schedule VARCHAR(8),
    room VARCHAR(6),
    CONSTRAINT Class_classNumber_pk PRIMARY KEY (classNumber),
    CONSTRAINT Class_facId_fk FOREIGN KEY (facId) REFERENCES Faculty
        (facId) ON DELETE SET NULL,
    CONSTRAINT Class_schedule_room_uk UNIQUE (schedule, room));

CREATE TABLE Enroll (
    stuId VARCHAR(6),
    classNumber VARCHAR(8),
    grade VARCHAR(2),
    CONSTRAINT Enroll_classNumber_stuId_pk PRIMARY KEY
        (classNumber, stuId),
    CONSTRAINT Enroll_classNumber_fk FOREIGN KEY (classNumber)
        REFERENCES Class (classNumber) ON DELETE CASCADE,
CONSTRAINT Enroll_stuId_fk FOREIGN KEY (stuId) REFERENCES Student
(stuId)ON DELETE CASCADE);

这是完整的命令和错误:

mysql> CREATE TABLE Class (classNumber VARCHAR(8), facId VARCHAR(6) NOT NULL, schedule VARCHAR(8), room VARCHAR(6), CONSTRAINT Class_classNumber_pk PRIMARY KEY (classNumber), CONSTRAINT Class_facId_fk FOREIGN KEY (facId) REFERENCES Faculty (facId) ON DELETE SET NULL, CONSTRAINT Class_schedule_room_uk UNIQUE (schedule, room));
ERROR 1005 (HY000): Can't create table 'university.Class' (errno: 150)

3 个答案:

答案 0 :(得分:2)

在facId

的定义中删除NOT NULL

答案 1 :(得分:0)

您是否首先创建了教师表。 查看此链接

inno db error

表示如果你得到错误150的1005,这意味着

未正确形成外键约束

答案 2 :(得分:0)

这是由于外键错误而发生的。要获得有关外键错误的更多详细信息,请运行SHOW ENGINE INNODB STATUS \ G并查看“最新外键错误”部分。

我认为它会告诉外键是无效的,因为Faculty.facid上没有唯一索引或主键索引。