Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

mysql - Failed to add the foreign key constraint. Missing index for constraint Error Code: 1822

So I'm trying to create a table 'Prerequisite_to', which is basically a relation that shows what classes are considered as a prerequisite for a specific class. Here are my SQL tables defections:

CREATE TABLE Class(
infs CHAR(4) NOT NULL,
course_number CHAR(3) NOT NULL,
PRIMARY KEY (infs,course_number));

CREATE TABLE Prerequisite_to(
    infs CHAR(4),
    course_number CHAR(3),
    PRIMARY KEY (infs,course_number),
    FOREIGN KEY (infs) REFERENCES Class(infs),
    FOREIGN KEY (course_number) REFERENCES Class(course_number)
)

However, when I execute the script I get this error:

17:29:43 CREATE TABLE Prerequisite_to( infs CHAR(4), course_number CHAR(3), PRIMARY KEY (infs,course_number), FOREIGN KEY (infs) REFERENCES Class(infs), FOREIGN KEY (course_number) REFERENCES Class(course_number) ) Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'prerequisite_to_ibfk_2' in the referenced table 'Class' 0.00038 sec

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have a composite primary key, so you need a composite foreign key:

CREATE TABLE Prerequisite_to(
    infs CHAR(4),
    course_number CHAR(3),
    PRIMARY KEY (infs,course_number),
    FOREIGN KEY (infs, course_number) REFERENCES Class(infs, course_number)
);

Just for the record, I'm not a fan of composite primary keys. I also think prerequisites need two course references. So:

CREATE TABLE Classes (
    class_id int auto_increment primary key,
    infs CHAR(4) NOT NULL,
    course_number CHAR(3) NOT NULL,
    unique (infs, course_number)
);

CREATE TABLE Prerequisites (
    preresequisite_id int auto_increment primary key,
    class_id int,
    prerequisite_class_id int,
    FOREIGN KEY (class_id) REFERENCES Classes(class_id),
    FOREIGN KEY (prerequisite_class_id) REFERENCES Classes(class_id)
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...