外键

 

创建外键

示例

科目表

create table classdepart
(
dep_id int identity primary key not null,
dep_part varchar(50)
)
go

  

职工信息表

create table teachinfo
(
	teach_id varchar(255) primary key not null,
	teach_name varchar(50) not null,
	teach_age int,
	teach_sex varchar(10) default('男'),
	teach_comp varchar(100),
	teach_phone varchar(20),
	teach_address varchar(255),
	teach_note varchar(300)
)
go

  

 

上面需要把职工信息表中的teach_comp列引用到dep_part列

因为是非主键,非候选键,如果要创建外键约束,那就必须都用unique约束

alter table classdepart
add unique(dep_part)
go

  

alter table teachinfo
add unique(teach_comp)
go

  

这时就可以创建外键约束了。

alter table teachinfo
add constraint fk_depart foreign key (teach_comp)
references classdepart(dep_part)
go

  

但是,因为姓名可能会重复一样的名字,所以无法用unique约束,这样的话,不如使用编 号来创建外键。一般编号都是主键。也不会重复。

 上面说的不能同时unique约束两个表的字段,所以只能约束引用的外键。比如这样。

create table stuclass
(
	stuid int primary key not null,
	stuname varchar(50),
	stutea int not null,
	stuseat int unique

)
go

  

上面创建了一个学生信息表,其中一个字段stutea表示任课教师,这里是无法用unique约束的,因为可能任课教师会重复。那么需要创建一个外表,里面是所有教师名称,做为外键。

create table teachername
(
	teaid int primary key not null,
	teaname varchar(50) unique
)
go

  

上面的教师信息表,teaname是不能做为外键的。因为它非主键,也不是候选键。就算改为int类型,也无法进行约束。因此只能用teaid这个字键来约束父表。

先给teachername录入数据。

insert into teachername (teaid,teaname) values(001,'张三')
insert into teachername (teaid,teaname) values(002,'李四')
insert into teachername (teaid,teaname) values(003,'陈五')
insert into teachername (teaid,teaname) values(004,'白七')
insert into teachername (teaid,teaname) values(005,'赫八')
go

  

再创建外键。

alter table stuclass
add constraint fk_teachername foreign key(stutea)
references teachername(teaid)
go

  

这样就创建了一个外键。

 

查询一下

select * from stuclass where stutea=(select teaid from teachername)
go
select a.stuid as '编号',a.stuname as '姓名',a.stuseat as '座位',c.teaname as '任课教师' from stuclass as a,teachername as c  where a.stutea=c.teaid
go

select * from teachername order by teaid asc
go

  

posted @ 2021-03-11 00:28  云中翱翔的鹏鸟  阅读(85)  评论(0编辑  收藏  举报