【发布时间】:2020-11-07 08:16:15
【问题描述】:
我通过创建 3 个表 (classes, lectures, taking) 来创建数据库,然后更改表以添加 foreign key。
但是,我不断收到以下错误:
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint
我似乎没有发现代码有任何问题,那么可能是什么问题? (我使用的是mySQL Workbench。我尝试复制粘贴为txt文件,因为我虽然可能是排序规则问题,但仍然会出现同样的问题)
代码如下:
CREATE TABLE classes (
course_id VARCHAR(8),
classes_id VARCHAR(10),
semester VARCHAR(10),
year VARCHAR(10),
PRIMARY KEY (course_id, classes_id, semester, year)
);
CREATE TABLE taking (
student_id VARCHAR(8),
course_id VARCHAR(10),
classes_id VARCHAR(10),
semester VARCHAR(10),
year VARCHAR(10),
grade char(1),
PRIMARY KEY (student_id, course_id, semester, year)
);
CREATE TABLE lectures (
professor_id VARCHAR(8),
course_id VARCHAR(10),
classes_id VARCHAR(10),
semester VARCHAR(10),
year VARCHAR(10),
PRIMARY KEY (professor_id, course_id, semester, year)
);
ALTER TABLE taking ADD CONSTRAINT consTAKE3 FOREIGN KEY(classes_id) REFERENCES classes(classes_id) ON DELETE CASCADE;
ALTER TABLE taking ADD CONSTRAINT consTAKE4 FOREIGN KEY(semester) REFERENCES classes(semester) ON DELETE CASCADE;
ALTER TABLE taking ADD CONSTRAINT consTAKE5 FOREIGN KEY(year) REFERENCES classes(year) ON DELETE CASCADE;
ALTER TABLE lectures ADD CONSTRAINT consLEC3 FOREIGN KEY(classes_id) REFERENCES classes(classes_id) ON DELETE CASCADE;
ALTER TABLE lectures ADD CONSTRAINT consLEC4 FOREIGN KEY(semester) REFERENCES classes(semester) ON DELETE CASCADE;
ALTER TABLE lectures ADD CONSTRAINT consLEC5 FOREIGN KEY(year) REFERENCES classes(year) ON DELETE CASCADE;
错误如下:
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'consTAKE3' in the referenced table 'classes'
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'consTAKE4' in the referenced table 'classes'
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'consTAKE5' in the referenced table 'classes'
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'consLEC3' in the referenced table 'classes'
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'consLEC4' in the referenced table 'classes'
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'consLEC5' in the referenced table 'classes'
现在,我正在尝试使用 ysql –u root –p 从 cmd 执行此操作。不过,同样的问题正在发生。
【问题讨论】: