4

我有一个 SQL Server 2008 数据库。这个数据库有三个表:

  - Id
  - FullName
  - MembershipStatusId (nullable)
  - HairStyleId (nullable)

会员状态

  - Id
  - Name

发型

  - Id
  - ColorName
  - Description

我需要创建一个查询,列出我数据库中的所有人员。因为MembershipStatusIdHairStyleId都可以为空,所以我知道我需要进行左外连接。但是,因为有多个表,我不知道该怎么做。通过一个左外连接,我知道我可以做到这一点:

SELECT
  p.*,
  m.Name as 'MembershipStatus',
  -- how do i include the person's hair color as part of my result set?
FROM
  Person p LEFT OUTER JOIN
    MembershipStatus m ON p.[MembershipStatusId]

但是,我不确定如何为发型名称添加左外连接。有人可以告诉我如何包含人的头发颜色吗?

谢谢!

4

2 回答 2

10

您只需再做一个LEFT JOIN以包含 HairStyle Table

SELECT
  p.*,
  m.Name as 'MembershipStatus',
  h.ColorName
FROM Person p 
LEFT JOIN MembershipStatus m 
    ON p.[MembershipStatusId] = m. Id
LEFT JOIN HairStyle h
    ON p.HairStyleId = h.id

查看关于SQL Fiddle的演示

于 2012-05-14T13:44:18.503 回答
1

也许是这样的:

SELECT
    Person.id,
    MembershipStatus.Name AS MemberShip,
    HairStyle.ColorName AS HairStyleColorName
FROM
    Person
    LEFT JOIN MembershipStatus
        ON Person.MembershipStatusId=MembershipStatus.Id
    LEFT JOIN HairStyle
        ON Person.HairStyleId = HairStyle.Id
于 2012-05-14T13:44:46.773 回答