无论是在学习耿老师视频,还是自考数据库原理,我们都接触到联合查询这部分,但在实践中并没有过多的去应用。现在做项目才真正认识到理论运用到实践的重要性。 一、概念 联合查询是根据每个表之间的逻辑关系从两个或多个表中检索数据 , 而这逻辑关系则是每个
无论是在学习耿老师视频,还是自考数据库原理,我们都接触到联合查询这部分,但在实践中并没有过多的去应用。现在做项目才真正认识到理论运用到实践的重要性。
一、概念
联合查询是根据每个表之间的逻辑关系从两个或多个表中检索数据,而这逻辑关系则是每个表之间共同的列的关联性,这也是关系数据库查询的最主要的特征.
数据表的连接有:
1、内连接
2、外连接
(1)左连接(左边表不限制)
(2)右连接(右边表不限制)
(3)全外连接(不受限制)
3、交叉连接
二、实践
建立两张表,一张学生管理表(t_managestudent)和学生信息表(t_studentinfo)
表1:(学生管理表):
表2:(学生信息表)
1、内连接
两表进行比较,满足连接条件的组合起来作为结果
语句:
方1: select dbo.t_managestudent.编号 as 编号1,dbo.t_managestudent.姓名, dbo.t_studentinfo.编号 as 编号2,dbo.t_studentinfo.职务 from t_managestudent inner join t_studentinfo on t_managestudent.编号=t_studentinfo.编号
方2: select a.编号 as 编号1,a.姓名,b.编号 as 编号2,b.职务 from t_managestudent as a inner join t_studentinfo as b on a.编号=b.编号
结果:
2、外连接
(1)左连接(左边表不限制)
返回结果集包含t_managestudent中所有记录,不仅仅是连接字段匹配的记录。如果t_managestudent中某条记录在t_studentinfo中没有匹配记录,则结果集相应记录有关t_studentinfo部分为null值
语句:
方1: select dbo.t_managestudent.编号 as 编号1,dbo.t_managestudent.姓名, dbo.t_studentinfo.编号 as 编号2,dbo.t_studentinfo.职务 from t_managestudent left join t_studentinfo on t_managestudent.编号=t_studentinfo.编号 方2: select a.编号 as 编号1,a.姓名,b.编号 as 编号2,b.职务 from t_managestudent as a left join t_studentinfo as b on a.编号=b.编号
结果:
(2)右连接(右边表不限制)
返回结果集包含t_studentinfo中所有记录,不仅仅是连接字段匹配的记录。如果t_studentinfot中某条记录在t_managestudent中没有匹配记录,则结果集相应记录有关t_managestudent部分为null值
语句:
方1: select dbo.t_managestudent.编号 as 编号1,dbo.t_managestudent.姓名, dbo.t_studentinfo.编号 as 编号2,dbo.t_studentinfo.职务 from t_managestudent right join t_studentinfo on t_managestudent.编号=t_studentinfo.编号 方2: select a.编号 as 编号1,a.姓名,b.编号 as 编号2,b.职务 from t_managestudent as a right join t_studentinfo as b on a.编号=b.编号
结果:
(3)全外连接(不受限制)
返回结果集包含t_managestudent和t_studentinfo所有匹配和不匹配的记录
语句:
方1: select dbo.t_managestudent.编号 as 编号1,dbo.t_managestudent.姓名, dbo.t_studentinfo.编号 as 编号2,dbo.t_studentinfo.职务 from t_managestudent full join t_studentinfo on t_managestudent.编号=t_studentinfo.编号
方2: select a.编号 as 编号1,a.姓名,b.编号 as 编号2,b.职务 from t_managestudent as a full join t_studentinfo as b on a.编号=b.编号
结果:
3、交叉连接
情况1(无where):
交叉连接将差生连接涉及的表的笛卡儿积,第一个表的行乘以第二个表的行等于笛卡儿积结果集的大小
情况2(有where):
同内连接一样
语句:
select t_managestudent.编号 as 编号1,t_managestudent.姓名,t_studentinfo.编号 as 编号2 from t_managestudent cross join t_studentinfo
结果: