SQL LEFT JOIN 左联接

SQL LEFT JOIN 关键字用来选择所有在左表中有匹配的记录,而不管在右表中是否有匹配。

SQL LEFT JOIN 语法

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

SQL LEFT JOIN 范例

数据表: Employees

EmployeeId FirstName LastName Department Salary
203 Mazojys Fxoj Finance 78000
204 Jozzh Lnanyo Finance 45800
205 Syllauu Dfaafk Finance 57000
206 Gecrrcc Srlkrt Finance 62000

数据表: Tickets

TicketID TicketNo EmployeeId
1 2349 203
2 2400 204
3 2438 205

选择所有的职员(Employees),如果它们有Tickets,列出Tickets:

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

结果会类似于:

EmployeeId FirstName LastName TicketNo
203 Mazojys Fxoj 2349
204 Jozzh Lnanyo 2400
205 Syllauu Dfaafk 2438
206 Gecrrcc Srlkrt

注:EmployeeID为206的职员在Tickets表中没有任何匹配,不过他仍然出现在结果集中,TicketNo值为null。