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。

4 Responses to SQL LEFT JOIN 左联接

  1. Nice article about left join with good example); good to see such kinds of article
    eGrove Systems recently posted..Welcome to BEST PMO

  2. FettesPS says:

    It’s amazing how many programmers dont know their joins. I’d say 99% never use anything more than an inner join :(

  3. SQL Tutor says:

    I agree left / right joins are very important but seldom used. Not relevant in some situation but when they are called for they do a much better job than inner joins. I guess people simply don’t know that they exist, and how they work.
    Nice tutorial.

  4. Daycare says:

    I use left joins all the time. Couldn’t imagine “life” without them :)

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*


*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv Enabled