连接查询:通过连接运算符可以实现多个表查询。连接是关系数据库模型的主要特点,也是它区别于其它类型数据库管理系统的一个标志。
常用的两个链接运算符:
1.join on
2.union
在关系数据库管理系统中,表建立时各数据之间的关系不必确定,常把一个实体的所有信息存放在一个表中。当检索数据时,通过连接操作查询出存放在多个表中的不同实体的信息。连接操作给用户带来很大的灵活性,他们可以在任何时候增加新的数据类型。为不同实体创建新的表,随后通过连接进行查询。
实例一
实例二
实例三
实例四
实例五
实例6
实例7
实例8
三个表的之间的数据查询:
练习一:
练习二
练习三
练习四
练习五
练习
创建三个表
成绩表 score
学生表 stu
老师表 tch
1 create table score 2 ( code int primary key identity(1001,1), 3 yu decimal(18,2), 4 shu decimal(18,2), 5 ying decimal(18,2), 6 ) 7 create table stu 8 ( scode int primary key identity(1001,1), 9 sname varchar(18),10 banji varchar(18),11 yujiao int,12 shujiao int,13 yingjiao int,14 )15 create table tch16 ( tcode int primary key identity(1,1),17 tname varchar(18),18 kemu varchar(18),19 )20 insert into score values(99,88,77)21 insert into score values(88,77,66)22 insert into score values(77,66,55)23 insert into score values(66,55,44)24 insert into score values(55,44,33)25 insert into score values(89,79,69)26 insert into score values(79,69,59)27 insert into score values(59,49,39)28 insert into tch values('玲玲','语文')29 insert into tch values('凌凌','语文')30 insert into tch values('灵灵','语文')31 insert into tch values('铃铃','数学')32 insert into tch values('媛媛','数学')33 insert into tch values('元元','数学')34 insert into tch values('圆圆','英语')35 insert into tch values('方方','英语')36 insert into tch values('芳芳','英语')37 insert into stu values('A','一班',2,4,8)38 insert into stu values('B','一班',1,5,7)39 insert into stu values('C','二班',3,6,9)40 insert into stu values('D','二班',2,4,8)41 insert into stu values('E','三班',1,5,7)42 insert into stu values('F','三班',3,6,9)43 insert into stu values('G','四班',2,4,7)44 insert into stu values('H','四班',1,5,9)45 select *from score46 select *from stu47 select *from tch48 49 select *from stu where yingjiao=(select tcode from tch where tname='圆圆')50 select stu.banji, score.shu from stu,score where score.code=stu.scode51 --查询此次考试语文最高分的学生信息52 select*from stu where scode=(select code from score where yu=(select MAX(yu) from score))53 --查询此次考试数学最低分的老师信息54 select * from tch where tcode in (55 (select yujiao from stu where scode=(select code from score where shu=(select MIN(shu)from score))),56 (select shujiao from stu where scode=(select code from score where shu=(select MIN(shu)from score))),57 (select yingjiao from stu where scode=(select code from score where shu=(select MIN(shu)from score)))58 )59 --查询汇总成一个表:各门课分数,学生姓名,班级,任课老师的姓名60 select stu.sname,banji,score.yu,shu,ying,61 (select tname from tch where tcode=yujiao) as 语文,62 (select tname from tch where tcode=shujiao) as 数学,63 (select tname from tch where tcode=yingjiao) as 英语64 from stu join score on stu.scode=score.code65 --查询每个班数学最高分66 select banji,MAX(shu) from stu join score on stu.scode=score.code group by banji67 --查询语文平均分最高的班级的老师信息68 select * from tch where tcode=69 ( select top 1 yujiao from stu where banji=70 ( select top 1 banji from stu join score 71 on stu.scode=score.code 72 group by banji order by AVG(yu) desc73 )74 )