MySQL错误:无法添加外键约束,但数据类型匹配

时间:2015-11-11 09:10:30

标签: mysql

我尝试使用外键创建表,但我不断收到错误1215,说它无法添加外键约束。我仔细检查了约束的数据类型和REFERENCES部分,这似乎是有序的。我在阅读了一些关于错误的MySQL文档之后添加了ENGINE = InnoDB,并没有解决它。我是创建新数据库的新手,所以我想我错过了一些东西。我可以添加什么来解决此错误?

CREATE DATABASE cemc;
USE cemc;

CREATE TABLE CALENDAR(
    year            INT                 NOT NULL,
    term            VARCHAR(25)         NOT NULL,
    term_start      DATE                NOT NULL,
    term_end        date                NOT NULL,

    CONSTRAINT      CALENDAR_PK         PRIMARY KEY(year, term)
)ENGINE=InnoDB;

CREATE TABLE COURSE(
    course_id       VARCHAR(6)          NOT NULL,
    skill           VARCHAR(25)         NOT NULL,
    level           VARCHAR(25)         NOT NULL,

    CONSTRAINT      COURSE_PK           PRIMARY KEY(course_id)
)ENGINE=InnoDB;

CREATE TABLE TEACHER(
    teacher_id      VARCHAR(50)         NOT NULL,
    teacher_last    VARCHAR(25)         NOT NULL,
    teacher_first   VARCHAR(25)         NOT NULL,
    email1          VARCHAR(50)         NOT NULL,
    email2          VARCHAR(50)         NULL,
    phone1          INT                 NOT NULL,
    phone2          INT                 NULL,

    CONSTRAINT      TEACHER_PK          PRIMARY KEY(teacher_id)  
)ENGINE=InnoDB;

CREATE TABLE COURSEASSIGNMENT(
    course_id       VARCHAR(6)          NOT NULL,
    year            INT                 NOT NULL,
    term            VARCHAR(25)         NOT NULL,
    teacher_id      VARCHAR(50)         NULL,
    room            VARCHAR(3)          NULL,

    CONSTRAINT      COURSEA_PK          PRIMARY KEY(course_id, term),
    CONSTRAINT      COURSEA_FK1         FOREIGN KEY(term)
                                        REFERENCES CALENDAR(term),
    CONSTRAINT      COURSEA_FK2         FOREIGN KEY(course_id)
                                        REFERENCES COURSE(course_id),
    CONSTRAINT      COURSEA_FK3         FOREIGN KEY(year)
                                        REFERENCES CALENDAR(year),
    CONSTRAINT      COURSEA_FK4         FOREIGN KEY(teacher_id)
                                        REFERENCES TEACHER(teacher_id)
)ENGINE=InnoDB;

2 个答案:

答案 0 :(得分:1)

问题是您尝试引用日历。到目前为止,您正在使用数据类型进行更正。但是日历有一个组合的主键。因此,您需要一次定义外键而不是两者分开,因为mysql将这两个解释为SEPARATE外键而不是组合外键。这导致它无法创建外键。

因此你需要这样做:

CONSTRAINT      COURSEA_PK          PRIMARY KEY(course_id, term),
CONSTRAINT      COURSEA_FK1         FOREIGN KEY(year, term)
                                    REFERENCES CALENDAR(year, term),
CONSTRAINT      COURSEA_FK2         FOREIGN KEY(course_id)
                                    REFERENCES COURSE(course_id),
CONSTRAINT      COURSEA_FK4         FOREIGN KEY(teacher_id)
                                    REFERENCES TEACHER(teacher_id)

答案 1 :(得分:0)

外键必须引用外表中的主键:

CONSTRAINT      COURSEA_FK1         FOREIGN KEY(term) REFERENCES CALENDAR(term)

并且term不是表格Calendar的PK。正确的形式应该是:

CONSTRAINT      COURSEA_FK1         FOREIGN KEY(year,term) REFERENCES CALENDAR(year,term)