Mysql 数据类型匹配时的错误代码:1822,使用复合键

Mysql 数据类型匹配时的错误代码:1822,使用复合键,mysql,foreign-keys,mysql-workbench,Mysql,Foreign Keys,Mysql Workbench,得到 错误代码:1822。未能添加外键约束。丢失的 引用表中约束“subject_ibfk_1”的索引 ‘入学’ 尝试创建主题表时。问题是,上一个表student中没有出现错误。数据类型相同,并且定义了主键 入学和成绩表都会出现此错误 create table enrolment( stud_id char(9) not null, subj_code char(8) not null, semester tinyint unsigned not null, ye

得到

错误代码:1822。未能添加外键约束。丢失的 引用表中约束“subject_ibfk_1”的索引 ‘入学’

尝试创建
主题
表时。问题是,上一个表
student
中没有出现错误。数据类型相同,并且定义了主键

入学
成绩
表都会出现此错误

create table enrolment(
    stud_id char(9) not null,
    subj_code char(8) not null,
    semester tinyint unsigned not null,
    year smallint unsigned not null,
    comment text,

    primary key (stud_id, subj_code, semester, year)
);

create table grade(
    stud_id char(9) not null,
    subj_code char(8) not null,
    semester tinyint unsigned not null,
    year smallint unsigned not null,
    grade tinyint unsigned,

    primary key (stud_id, subj_code, semester, year)
);

create table student(
    stud_id char(9) not null,
    stud_name char(30),
    stud_phone char(12),
    stud_date_of_birth date,
    stud_city char(26),
    stud_address char(30),
    stud_postcode char(4),

    primary key (stud_id),

    foreign key (stud_id)
        references grade(stud_id),
    foreign key (stud_id)
        references enrolment(stud_id)
);

create table subject(
    subj_code char(8) not null,
    subj_title char(40),

    primary key (subj_code),

    foreign key (subj_code)
        references enrolment(subj_code),

    foreign key (subj_code)
        references grade(subj_code)
);

该问题是由于外键
subc_code
是引用表
中多列主键(PK)的一部分:

primary key (stud_id, subj_code, semester, year)
其中,此列(
subc\u code
)不是最左边的一列

student
没有此问题,因为其外键列
stud_id
是引用表中PK的最左边的列

要解决此问题,可以为引用列创建新索引:

ALTER TABLE enrolment ADD INDEX subj_code_idx (subj_code);
注意:您必须对其他外键中的引用表
等级
执行相同操作


这是可行的,但是为什么为列创建新索引可以解决问题呢?