use master
go
if exists (select * from sysdatabases where name ='testDB')
drop database testDB
go
create database testDB
go
-----------------stu
if exists (select * from sysobjects where name='un_sno')
alter table t_stu drop constraint un_sno
if exists (select * from sysobjects where name='fk_sno')
alter table t_score drop constraint fk_sno
if exists (select * from sysobjects where name='t_stu')
drop table t_stu
go
create table t_stu(
sno varchar(8) primary key,
sname varchar(12) not null,
sclass varchar(20),
sgrade int
)
go
------------------subject
if exists (select * from sysobjects where name='fk_subid')
alter table t_score drop constraint fk_subid
if exists (select * from sysobjects where name='t_subject')
drop table t_subject
go
create table t_subject(
subid int primary key identity(1,1),
suname varchar(16)
)
go
-----------------score
if exists (select * from sysobjects where name='t_score')
drop table t_score
go
create table t_score(
scid int primary key identity(1,1),
sno varchar(8) not null,
subid int,
sscore int
)
go
---------------constraints
alter table t_stu add constraint un_sno unique (sno)
go
alter table t_score add constraint fk_sno foreign key (sno)
references t_stu(sno)
go
alter table t_score add constraint fk_subid foreign key (subid)
references t_subject(subid)
go
---------------insert value
insert into t_stu values('001','tom','s3',2)
insert into t_stu values('002','jack','s4',3)
insert into t_stu values('003','ann','e3',3)
insert into t_stu values('004','jim','e4',6)
insert into t_subject values('历史')
insert into t_subject values('哲学')
insert into t_subject values('英语')
insert into t_score values('001',2,89)
insert into t_score values('001',3,49)
insert into t_score values('003',3,83)
insert into t_score values('001',1,84)
---------------display
select * from t_stu
select sno ,sname from t_stu
select * from t_score
select * from t_subject
--------------result
select a.sno as '学号' ,a.sname,b.suname as '学科',c.sscore as '分数' from t_score as c
left join t_score as a on a.sno=c.sno
left join t_subject as b on b.subid=c.subid