在SQL中,如何在复合主键上创立外键?

2024-12-03 19:21:41
推荐回答(2个)
回答1:

--不能一列引用两列,必髯数列对应
use tempdb
go
create table s
(
sid varchar(20),
sname varchar(20),
ssex varchar(2) check(ssex='男' or ssex='女') default '男',
sage int check(sage between 0 and 100),
sclass varchar(20),
constraint event_key primary key (sid,sclass)----创建复合主键
)

create table t
(
teacher varchar(20) primary key,
sid varchar(20) not null,
sclass varchar(20) not null,
num int,
foreign key(sid,sclass) references s(sid,sclass)
)

回答2:

语法:
①创建时:create table sc (
studentno int,
courseid int,
score int,
foreign key (courseid) );
②修改时:
ALTER TABLE news_info[子表名] ADD CONSTRAINT FK_news_info_news_type[约束名] FOREIGN KEY (info_id)[子表列] REFERENCES news_type[主表名] (id)[主表列] 。