单表中的SQL双外键

时间:2017-02-26 18:35:10

标签: mysql sql

我是一名sql初学者。我正在创建一个数据库来跟踪学生在学校的入学情况。

我使用以下方法创建了前3个学生,学校和班级(数据库必须跟踪学生所在的班级):

CREATE TABLE Students (
        studId int NOT NULL AUTO_INCREMENT primary key,
        name varchar(20),
        surname varchar(20),
        birthDate date,
        birthPlace varchar(40)
    );

CREATE TABLE Schools (
    schId varchar(20) NOT NULL primary key,
    name varchar(50),
    province char(2),
    region varchar(20)
);

CREATE TABLE Classes (
    classId int NOT NULL AUTO_INCREMENT,
    schId varchar(20),
    FOREIGN KEY (schId) REFERENCES Schools(schId),
    PRIMARY KEY (classId, schId),
    name varchar(5),
    course varchar(20),
    option varchar(20)
);

现在,我需要一个Enroll表,但这会导致错误:

CREATE TABLE Enrolls(
    studId int,
    schId varchar(20),
    classId varchar(20),
    FOREIGN KEY (schId) REFERENCES Schools(schId),
    FOREIGN KEY (studId) REFERENCES Students(studId),
    FOREIGN KEY (classId) REFERENCES Classes(classId),
    PRIMARY KEY(studId, schId, classId)
);

我想因为classId是Classes表中带有schId的主键。

我该如何解决?

  

错误1005(HY000):无法创建表studentsdb.enrolls(错误:150“外键约束形成错误”)

3 个答案:

答案 0 :(得分:0)

Classes.classId是一个整数,而Enrolls.classId是一个varchar。

答案 1 :(得分:0)

我希望能够解决错误

classID中的Enrolls类型为varchar(20),表Classes中的int类型为public class MyClass { private const long SOME_VALUE= (10 * 1024 * 1024 * 1024); // 10 GB .... }

确保它们都具有相同的类型。 错误将消失!!

答案 2 :(得分:0)

请尝试在代码

下运行

尝试在sqlfiddle上成功运作。标记的更改。

Sqlfiddle链接 - http://sqlfiddle.com/#!9/f7dd7/1/0

CREATE TABLE Students (
        studId int NOT NULL AUTO_INCREMENT primary key,
        name varchar(20),
        surname varchar(20),
        birthDate date,
        birthPlace varchar(40)
    );

CREATE TABLE Schools (
    schId varchar(20) NOT NULL primary key,
    name varchar(50),
    province char(2),
    region varchar(20)
);

CREATE TABLE Classes (
    classId int NOT NULL AUTO_INCREMENT,
    schId varchar(20),
    name varchar(5),
    course varchar(20),
    option_a varchar(20), -- not accepting column name "option"
  FOREIGN KEY (schId) REFERENCES Schools(schId),
  PRIMARY KEY (classId, schId)
);


CREATE TABLE Enrolls(
    studId int, --changed data type to int i think due to which issue was coming also suggested in other answers.
    schId varchar(20),
    classId int,
    FOREIGN KEY (schId) REFERENCES Schools(schId),
    FOREIGN KEY (studId) REFERENCES Students(studId),
    FOREIGN KEY (classId) REFERENCES Classes(classId),
    PRIMARY KEY(studId, schId, classId)
);