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

时间:2018-08-29 06:24:44

标签: mysql foreign-keys mysql-workbench

获取

  

错误代码:1822。无法添加外键约束。失踪   引用表中约束“ subject_ibfk_1”的索引   “入学”

尝试创建subject表时。问题是,上一张表student上不会发生此错误。数据类型相同,并且定义了主键。

enrolmentgrade表都发生此错误。

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)
);

1 个答案:

答案 0 :(得分:0)

问题是由于以下事实:外键subj_code是引用表enrolment多列主键(PK)的一部分:

primary key (stud_id, subj_code, semester, year)

此列(subj_code)不是最左边的

student不会出现此问题,因为它的外键列stud_id是所引用表中PK的最左列。

要解决此问题,您可以为所引用的列创建一个新索引:

ALTER TABLE enrolment ADD INDEX subj_code_idx (subj_code);

注意:您必须对另一个外键中的引用表grade执行相同的操作。

Demo here