SqlServer--多表之间的数据查询

以下是学习笔记:

1,内连接查询:2张表的查询  

内连接查的是:几张表之间的公共部分,与表的先后顺序没有关系

--内连接查询,两张表查询
select Students.StudentId,C#成绩=CSharp,StudentName --StudentId是公共字段,必须要说明是哪张表的StudentId,这里写 Students.StudentId或者ScoreList.StudentId都可以
from ScoreList  --哪个表的字段表较多或者要查询的内容集中在哪张表中,就把那张表写在这里,from后面的ScoreList和inner join后面的Students可以交换位置的
inner join Students on  Students.StudentId=ScoreList.StudentId --第一张表
 where CSharp >80

 --内连接查询,两张表查询
select ScoreList.StudentId,C#成绩=CSharp,StudentName --StudentId是公共字段,必须要说明是哪张表的StudentId 
from Students  --哪个表的字段表较多或者要查询的内容集中在哪张表中,就把那张表写在这里
inner join ScoreList on  Students.StudentId=ScoreList.StudentId --第一张表
 where CSharp >80

  

【举例2】

2,内连接查询:3张表的查询

 --内连接查询,三张表表查询
select Students.StudentId,C#成绩=CSharp,StudentName,ClassName --StudentId是公共字段,必须要说明是哪张表的StudentId 
from ScoreList  --哪个表的字段表较多或者要查询的内容集中在哪张表中,就把那张表写在这里
inner join Students on  Students.StudentId=ScoreList.StudentId --第一张表
inner join StudentClass on Students.ClassId=StudentClass.ClassId  --第二张表
 where CSharp >80

 3,左外连接

 --左外连接查询 表的位置先后位置有关系,首先满足左表的所有数据
 --查询的结果包括2个表所有满足连接条件的记录。以及 左表有所不满足条件的其他记录。这些不满足的左表记录,在结果的右边位置,全部天上NULL值
select  Students.StudentId,StudentName,Gender ,C#成绩=CSharp from Students  --从Students表中查询,from后面代表的是左边,左表
left outer join ScoreList on Students.StudentId=ScoreList.StudentId
where Gender='男'

select  Students.StudentId,StudentName,Gender ,C#成绩=CSharp from ScoreList --从ScoreList表中查询
left outer join Students on Students.StudentId=ScoreList.StudentId
where Gender='男'

select  Students.StudentId,StudentName,Gender ,C#成绩=CSharp from ScoreList --从ScoreList表中查询
left join Students on Students.StudentId=ScoreList.StudentId --outer关键字去掉也可以的,标准写法我们还是带outer
where Gender='男'

  4,右外连接

待更新。。。

 

原文地址:https://www.cnblogs.com/baozi789654/p/13910232.html