Sql Server:多表连接查询

查询一天所有的信息:

select *(查询内容) from (表名) where (时间)>设定时间 and (时间)<设定时间

select * from StudentBindPaperTypeEntity where StudentBindPaperTypeEntity.TimeTamp > '2019-01-04 00:00:00' and StudentBindPaperTypeEntity.TimeTamp< '2019-01-05 00:00:00'
多表连接查询:通过连接运算符来实现多张表连接数据查询。
分类:内连接(分为连接分为等值连接、自然连接和自连接三种。 ),外连接(分为左外连接,右外连接,全外连接)

内连接,关键字(inner join)

定义:两个表都满足where条件的数据留下。如下图的满足where条件交集部分。
在这里插入图片描述
select (查询内容)
from 表1 as a with(nolock)
inner join 表2 as b with(nolock)
on a.时间字段=b.时间字段(这个地方填两个表内容相同的数据)
where (条件)

select * 
from ScoreEntity as a with(nolock)
inner join StudentBindPaperTypeEntity as b with(nolock) 
 on a.timeSpan=b.TimeTamp 
 where b.TimeTamp > '2019-01-04 00:00:00' and b.TimeTamp< '2019-01-05 00:00:00'

外连接:

左连接(左外连接),关键字:left join on / left outer join on

定义:显示关键字left左边表中所有数据都会展示出来,右边表仅仅展示符合条件的数据,右边表在左边没有匹配数据的地方补null。
在这里插入图片描述

select * 
from ScoreEntity as a with(nolock)
left outer join StudentBindPaperTypeEntity as b with(nolock) 
 on a.timeSpan=b.TimeTamp 
 where b.TimeTamp > '2019-01-04 00:00:00' and b.TimeTamp< '2019-01-05 00:00:00'
右连接(右外连接),关键字:right join on / right outer join on:

定义:显示关键字right右边表中所有数据,左边表仅仅展示符合搜索条件的数据,左边表在右边表没有匹配数据的地方补null。
在这里插入图片描述

select * 
from ScoreEntity as a with(nolock)
right outer join StudentBindPaperTypeEntity as b with(nolock) 
 on a.timeSpan=b.TimeTamp 
 where b.TimeTamp > '2019-01-04 00:00:00' and b.TimeTamp< '2019-01-05 00:00:00' 
全连接(全外连接),关键字:full join on / full outer join on

**定义:**返回两个连接中所有的记录数据,是左外连接和右外连接的并集。
在这里插入图片描述
查询两张表,他们时间字段相同。通过这个时间字段来连接。
select (查询内容)
from 表1 as a(定义为a) with(nolock)
full outer join 表2 as b(定义为b) with(nolock)
on a.时间字段=b.时间字段
where b.时间字段> and b.时间字段<

select * 
from ScoreEntity as a with(nolock)
 full outer join StudentBindPaperTypeEntity as b with(nolock) 
 on a.timeSpan=b.TimeTamp 
 where b.TimeTamp > '2019-01-04 00:00:00' and b.TimeTamp< '2019-01-05 00:00:00'
发布了96 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Ciel_Y/article/details/103468703