多表连接(join)查询是指通过多张表之间共同列的相关性来查询数据。
多表连接一般有内连接(inner join)、左外连接(left join)、右外连接(right join)、完全外连接(full outer join)
区别:
inner join:表中有至少一个匹配,则返回行
left join:右表中没有匹配,也从左表返回所有的行
right join:左表中没有匹配,也从右表返回所有的行
full outer join:返回左表和右表中所有的行
示例:
表的定义如下
create table [dbo].[Students](
[StuId] [int] not null,
[StuName] [nvarchar](50) not null,
[StuDept] [nvarchar](50) not null,
[StuAge] [int] not null
)
create table [dbo].[StuScores](
[StuId] [int] not null,
[CusId] [int] not null,
[Score] [float] not null,
[TestDate] [datetime] null
)
普通查询:
select * from[dbo].[Students]
select * from[dbo].[StuScores]
1.内连接(inner join)
inner join 关键字在表中存在至少一个匹配时返回行。
语法:
select column_name(s)
from table1
inner join table2
on table1.column_name=table2.column_name
示例:
查询学生姓名、学号、课程及成绩
select A.StuName ,A.StuId,B.CusId ,B.Score
from [dbo].[Students] A
inner join[dbo].[StuScores] B
on A.StuId =B.StuId
注意由于是表中存在至少一个匹配时返回行,所以返回行中是缺少这些没有匹配的数据
2.左外连接(left join)
left join 关键字从左表(table1)返回所有的行,即使右表(table2)中没有匹配。如果右表中没有匹配,则结果为 NULL。
语法:
select column_name(s)
from table1
left join table2
on table1.column_name=table2.column_name
示例:
查询全部学生学号、课程号、成绩及姓名
select A.StuId ,A.CusId ,A.Score ,B.StuName
from [dbo].[StuScores] A
left join [dbo].[Students] B
on A.StuIdchax =B.StuId
从左表(StuScores)返回所有的行,即使右表(Students)中没有匹配。
3.右外连接(right join)
right join关键字从右表(table2)返回所有的行,即使左表(table1)中没有匹配。如果左表中没有匹配,则结果为 NULL。
语法:
select column_name(s)
from table1
right join table2
on table1.column_name=table2.column_name
示例:
查询全部学生学号、课程号、成绩及姓名
select A.StuId ,A.CusId ,A.Score ,B.StuName
from [dbo].[StuScores] A
right join [dbo].[Students] B
on A.StuId =B.StuId
从右表(Students)返回所有的行,即使左表(StuScores)中没有匹配。
4.完全外连接(full outer join)
full outer join关键字只要左表(table1)和右表(table2)其中一个表中存在,则返回行。
语法:
select column_name(s)
from table1
full outer join table2
on table1.column_name=table2.column_name
示例: 查询全部学生学号、课程号、成绩及姓名
select A.StuId ,A.CusId ,A.Score ,B.StuName
from [dbo].[StuScores] A
full outer join [dbo].[Students] B
on A.StuId =B.StuId
返回左表(StuScores)和右表(Students)中所有的行
end
有兴趣的小伙伴可以关注“SQL数据库笔记”公众号,一起学习吧!