我的脚本
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,并且签名定义相同,这到底是什么错误?任何帮助表示赞赏。
答案 0 :(得分:3)
您还需要指定引用另一张表中的哪一列,因此例如,外键声明需要为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)
);
答案 1 :(得分:1)
您还需要指定要引用的表的列。在您的情况下,这就是您的写法:
create table grade
(
[...]
foreign key(stud_id) references student (stud_id),
foreign key(sub_code) references subject (sub_code)
);