连接查询:通过连接运算符可以实现多个表查询。连接是关系数据库模型的主要特点,也是它区别于其它类型数据库管理系统的一个标志。
常用的两个链接运算符:
1.join on
2.union
在关系数据库管理系统中,表建立时各数据之间的关系不必确定,常把一个实体的所有信息存放在一个表中。当检索数据时,通过连接操作查询出存放在多个表中的不同实体的信息。连接操作给用户带来很大的灵活性,他们可以在任何时候增加新的数据类型。为不同实体创建新的表,随后通过连接进行查询。
示例一:
示例二:
示例三:
示例四:
示例五:
示例六:
示例七:
示例八:
练习:
create database lianxi119 go use lianxi119 go create table score ( code int primary key identity(1001,1), yu decimal(10,2), shu decimal(10,2), ying decimal(10,2), ) go create table Student ( scode int primary key identity(1001,1), sname varchar(10), banji varchar(10), yujiao int, shujiao int, yingjiao int, ) go create table Teacher ( tcode int primary key identity(1,1), tname varchar(10), tkemu varchar(10), ) go insert into score values(99,88,77) insert into score values(88,77,66) insert into score values(77,66,55) insert into score values(66,55,44) insert into score values(55,44,33) insert into score values(89,79,69) insert into score values(79,69,59) insert into score values(59,49,39) select *from score insert into Student values('A','一班',2,4,8) insert into Student values('B','一班',1,5,7) insert into Student values('C','二班',3,6,9) insert into Student values('D','二班',2,4,8) insert into Student values('E','三班',1,5,7) insert into Student values('F','三班',3,6,9) insert into Student values('G','四班',2,4,7) insert into Student values('H','四班',1,5,9) select *from Student insert into Teacher values('玲玲','语文') insert into Teacher values('凌凌','语文') insert into Teacher values('灵灵','语文') insert into Teacher values('铃铃','数学') insert into Teacher values('媛媛','数学') insert into Teacher values('元元','数学') insert into Teacher values('圆圆','英语') insert into Teacher values('方方','英语') insert into Teacher values('芳芳','英语') select *from Teacher --查询此次语文考试成绩最高的学生 select *from Student where scode =(select code from score where yu =(select MAX(yu)from score)) --查询此次数学考试成绩最低的学生的任课教师的信息 select *from Teacher where tcode =(select shujiao from Student where scode =(select code from score where shu=(select MAX(shu)from score))) --查询汇总成一个表:各门课分数、学生姓名、班级、任课老师的信息 select Student.sname,score.shu,score.ying,score.yu,(select tname from Teacher where tcode = Student.shujiao)as 数学老师, (select tname from Teacher where tcode = Student.yingjiao)as 英语老师, (select tname from Teacher where tcode = Student.yujiao)as 语文老师 from Student join score on Student.scode =score.code