外键不正确formed:mysql

tvokkenx  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(384)

我的剧本

create table student
(
stud_id int(9) unsigned not null,
stud_name varchar(30),
stud_phone int(10),
stud_dob date,
stud_city varchar(15),
stud_address varchar(50),
stud_postcode int(5),
primary key(stud_id)
);

create table subject
(
sub_code varchar(9) not null,
sub_title varchar(30),
primary key(sub_code)
);

create table grade
(
stud_id int(9) unsigned not null,
sub_code varchar(9) not null,
sem int(1) not null,
year int(4) not null,
comment varchar(50),
primary key(stud_id,sub_code,sem,year),
foreign key(stud_id) references student,
foreign key(sub_code) references subject
);

我不知道为什么它没有引用,我对sql还很陌生。列数据类型相同,排序规则都是latin1,签名定义也相同,到底出了什么问题?感谢您的帮助。

cgh8pdjw

cgh8pdjw1#

您还需要指定要引用的表的列。在你的情况下,你是这样写的:

create table grade
(
[...]
foreign key(stud_id) references student (stud_id),
foreign key(sub_code) references subject (sub_code)
);

外键上的mysql doc

jtoj6r0c

jtoj6r0c2#

您还需要指定引用另一个表中的哪一列,因此需要修改外键声明 foreign key(stud_id) references student(stud_id) 例如。
例如:

create table subject
(
sub_code varchar(9) not null,
sub_title varchar(30),
primary key(sub_code)
);

create table grade
(
stud_id int(9) unsigned not null,
sub_code varchar(9) not null,
sem int(1) not null,
year int(4) not null,
comment varchar(50),
primary key(stud_id,sub_code,sem,year),
foreign key(sub_code) references subject(sub_code)
);

相关问题