SQL Sever 数据库基础
--使用master数据库
use master
go
--判断是否已存在student数据库,如果存在就删除掉
if exists (select * from sys.databases where name ='student')
drop database student
--创建student数据库
create database student
go
--创建stuinfo学生表
create table stuinfo
(
stuid int primary key identity(1,1),--学号(主键,自动增长列)
stuname varchar(20) not null,--姓名
stusex varchar(2) not null,--性别
)
--创建score成绩表
create table score
(
scoid int primary key identity(1,1),--考号(主键,自动增长列)
stuid int references stuinfo(stuid),--学号(外键)
subject varchar(20) not null, --科目
scored int not null,--成绩
)
go
--插入stuinfo学生表数据
--单行插入
insert into stuinfo(stuname,stusex) values('孙一','男')
insert into stuinfo(stuname,stusex) values('钱二','男')
insert into stuinfo(stuname,stusex) values('赵一','女')
insert into stuinfo(stuname,stusex) values('张三','男')
insert into stuinfo(stuname,stusex) values('李四','女')
insert into stuinfo(stuname,stusex) values('王五','女')
insert into stuinfo(stuname,stusex) values('赵六','男')
--插入score成绩表数据
--单行插入
insert into score(stuid,subject,scored) values (1,'sql',95)
insert into score(stuid,subject,scored) values (2,'sql',96)
insert into score(stuid,subject,scored) values (3,'sql',84)
insert into score(stuid,subject,scored) values (4,'sql',77)
insert into score(stuid,subject,scored) values (5,'sql',73)
insert into score(stuid,subject,scored) values (6,'sql',98)
insert into score(stuid,subject,scored) values (7,'sql',84)
--查询stuinfo学生表
select * from stuinfo
--查询score成绩表
select * from score
--内部联接查询(inner join ... on...)
select * from stuinfo inner join score on stuinfo.stuid=score.stuid
--带条件的内部联接查询(inner join ... on... where)
select stuinfo.stuid 学号,stuinfo.stuname 姓名,stuinfo.stusex 性别,score.subject 科目,score.scored 成绩
from stuinfo inner join score on stuinfo.stuid=score.stuid where score.scored>=90
--外部联接查询(左联接/右联接 left/right)
select stuinfo.stuid 学号,stuinfo.stuname 姓名,stuinfo.stusex 性别,score.subject 科目,score.scored 成绩
from stuinfo left join score on stuinfo.stuid=score.stuid
--交叉联接
select COUNT(*) stuinfo记录 from stuinfo
select COUNT(*) score记录 from score
select COUNT(*) 交叉连接记录 from stuinfo cross join score
--集合运算(union/union all)
select score.stuid 学号,score.subject 科目,score.scored 成绩
from score where scored>=80
union
select stuid,subject,scored from score
where stuid=3
--使用intersect进行交集运算
select score.stuid 学号,score.subject 科目,score.scored 成绩
from score where scored>=90
intersect
select score.stuid,score.subject,score.scored
from score where stuid=3
--使用except进行交集运算
select score.stuid,score.subject,score.scored from score
where scored>=85
except
select score.stuid,score.subject,score.scored
from score where stuid=3
--修改(update...set...where...)
update stuinfo set stuname='修改',stusex='男' where stuinfo.stuid=3
select * from stuinfo
--删除
delete from score where scored=1 --用于删除表中的数据delete(deleted from... where...)
truncate table score--删除数据表中所有记录truncate table(truncate table...)