得到一个
错误代码:1822。未能添加外键约束。引用的表“registration”中缺少约束“subject\u ibfk\u 1”的索引
尝试创建 subject
table。问题是,错误不会出现在上一个表上 student
. 数据类型相同,并且定义了主键。
此错误发生在 enrolment
以及 grade
table。
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条答案
按热度按时间nfs0ujit1#
这个问题是由于外键,
subj_code
,是引用表中多列主键(pk)的一部分enrolment
:这个专栏在哪里(
subj_code
)不是最左边的。表
student
不存在此问题,因为其外键列stud_id
是引用表中pk的最左边的列。要解决此问题,可以为引用列创建新索引:
注意:对于引用的表,必须执行相同的操作
grade
在另一个外键中。此处演示