SQL RIGHT JOIN 右联接

SQL RIGHT JOIN 关键字与SQL LEFT JOIN 关键字非常相似,它会选择所有在右表中匹配的记录,而不管在左表中是否有匹配。

SQL RIGHT JOIN 语法

SELECT Table1.Column1, Table1.Column2, ... , Table2.Column1, Table2.Column2, ...
FROM Table1
RIGHT JOIN Table2
ON Table1.ColumnName = Table2.ColumnName

SQL RIGHT JOIN 范例

数据表: Employees

EmployeeId FirstName LastName Department Salary
203 Ahooc Yuish Finance 78000
204 Quisheen Nnuchen Finance 45800
205 Lshhwe Aceed Finance 57000

数据表: Tickets

TicketID TicketNo EmployeeId
1 2200 203
2 2338 204
3 2369 205
4 2410 206

选择所有的Tickets,如果它属于某个职员(Employee),列出该职员(Employee):

SELECT Employees.EmployeeId
           , Employees.FirstName
           , Employees.LastName
           , Tickets.TicketNo
FROM Employees
RIGHT JOIN Tickets
ON Employees.EmployeeId = Tickets.EmployeeId

结果会类似于:

EmployeeId FirstName LastName TicketNo
203 Ahooc Yuish 2200
204 Quisheen Nnuchen 2338
205 Lshhwe Aceed 2369
2410

注:Ticket 2410不属于任何任何Employee,但它还是出现在结果集中,其中Employee信息为null。