复合主键之一做外键

来源:百度知道 编辑:UC知道 时间:2024/06/08 16:01:48
有a,b两张表,
a的主键是no1和no2组成的复合主键
现在b表中用a表的no1做外键,怎么做
create table Course
(
CourseCode int not null,
CourseType varchar(10) primary key(CourseType,CourseCode),

)
create table Students
(
CourseCode int
)
alter table Students add constraint fk_s_c foreign key (CourseCode) references Course(CourseCode)
出现:在被引用表 'Course' 中没有与外键 'fk_s_c' 的引用列的列表匹配的主键或候选键的错误提示
表student中只有coursecode,并没有coursetype.

复合主键之一不能为 别的表的字段的参照外键啊

你想想(CourseType,CourseCode)为主键的话CourseCode的值是可以重复的!
比如:(1,2),(2,2)

所以。。

引用两个字段
alter table Students add CourseType varchar(10)
alter table Students add constraint fk_s_c foreign key (CourseType,CourseCode) references Course(CourseType,CourseCode)