SQL SERVER LEFT JOIN, INNER JOIN, RIGHT JOIN

Posted Jesse_Li

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL SERVER LEFT JOIN, INNER JOIN, RIGHT JOIN相关的知识,希望对你有一定的参考价值。

  • JOIN: 如果表中有至少一个匹配,则返回行
  • LEFT JOIN: 即使右表中没有匹配,也从左表返回所有的行
  • RIGHT JOIN: 即使左表中没有匹配,也从右表返回所有的行
  • FULL JOIN: 只要其中一个表中存在匹配,就返回行
CREATE TABLE dbo.Student
(
 Sno int  null
,Name nvarchar(23) 
)
CREATE TABLE dbo.Score
(
 Sno int 
,Score INT
)
INSERT INTO dbo.Student(Sno,Name)VALUES(1,\'Jesse\');
INSERT INTO dbo.Student(Sno,Name)VALUES(2,\'Jessca\');
INSERT INTO dbo.Student(Sno,Name)VALUES(3,\'June\');
INSERT INTO dbo.Student(Sno,Name)VALUES(4,\'Supper\');

INSERT INTO dbo.Score(Sno,Score)VALUES (1,45)
INSERT INTO dbo.Score(Sno,Score)VALUES (1,56)
INSERT INTO dbo.Score(Sno,Score)VALUES (2,100)
INSERT INTO dbo.Score(Sno,Score)VALUES (3,25)  


 查看数据:

SELECT * FROM dbo.Student
SELECT * FROM dbo.Score

  

Left Join 会显示出左边的全部数据,右边如果没有对应的值,系统默认NULL

SELECT *
FROM dbo.Student a
LEFT JOIN dbo.Score b
ON a.Sno=b.Sno

  

INNER JOIN 显示交集

SELECT *
FROM dbo.Student a
INNER JOIN dbo.Score b
ON a.Sno=b.Sno

  

right join 右表全部显示,左表没有,默认设置为NULL

SELECT *
FROM dbo.Student a
RIGHT JOIN dbo.Score b
ON a.Sno=b.Sno

  

FULL JOIN 左右边都显示,如果对方没有值得统一设置NULL

SELECT *
FROM dbo.Student a
FULL JOIN dbo.Score b
ON a.Sno=b.Sno

  

 

以上是关于SQL SERVER LEFT JOIN, INNER JOIN, RIGHT JOIN的主要内容,如果未能解决你的问题,请参考以下文章

INNER JOIN与LEFT JOIN在SQL Server的性能

SQL Server JOINS:SQL Server 中是不是默认关联“JOIN”语句“LEFT OUTER”? [复制]

SQL SERVER LEFT JOIN, INNER JOIN, RIGHT JOIN

sql server join ,inner join ,left join ,right join 的使用

SQL GROUP BY 与 LEFT JOIN MS SQL Server

SQL Server LEFT OUTER JOIN 查询性能