SQL - 使用左连接混合内连接

时间:2011-09-05 13:50:22

标签: sql

我有一个包含三个表的SQL Server数据库:Gang,GangMember和Neighborhood。这些表的结构如下:

Neighborhood
------------
ID (non-null)
Name (non-null)

Gang
----
ID (non-null)
Name (non-null)
NeighborhoodID (nullable)

GangMember
----------
ID (non-null)
GangID (non-null)
Name (non-null),
Position (nullable)

我需要帮派成员所属的所有帮派(是的,他们可以属于多个)。如果有一个社区,我也需要返回。我希望我的结果集的形式为:gang.name,neighborhood.name,member.position

到目前为止,我已经到了这里:

SELECT
 g.[Name],
 '' as 'Neighborhood' /* This what I don't know how to do */
 m.[Position]
FROM
  [Gang] g, 
  [GangMember] m
WHERE
  m.[GangID]=g.[ID]

因为一个团伙可能没有社区,我不知道如何完成这个查询。有人可以帮帮我吗?谢谢!

4 个答案:

答案 0 :(得分:5)

试试这个:

SELECT
  g.[Name],
  n.[Name] as 'Neighborhood',
  m.[Position]
FROM 
  [Gang] g INNER JOIN [GangMember] m ON m.[GangID]=g.[ID]
  LEFT OUTER JOIN [Neighborhood] n ON g.[NeighborhoodID] = n.[ID]

答案 1 :(得分:1)

select G.Name as GangName,
       N.Name as Neighborhood,
       GM.Name as MemberName,
       GM.Position as MemberPosition
from Gang as G
  inner join GangMember as GM
    on G.ID = GM.GangID
  left outer join Neighborhood as N
    on G.NeighborhoodID = N.ID

答案 2 :(得分:0)

您可以按如下方式进行左连接:

SELECT 
 g.[Name], 
 n.name as 'Neighborhood' /* This what I don't know how to do */ 
 m.[Position] 
FROM 
  [Gang] g 
  INNER JOIN [GangMember] m ON m.[GangID]=g.[ID]
  LEFT JOIN Neighborhood n ON n.Id = g.NeighborhoodID

答案 3 :(得分:0)

SELECT TOP (100) PERCENT
    DemographicTable.Name,
    ReferralTable.Code,
    ReferralTable.Date_Termed,
    ReferralTable.Referral_date,
    (
        SELECT Date_Accepted
        FROM CaseTable
        WHERE (ReferralTable.ID = DemographicTable.ID_Number)
            AND (Date_Accepted <> '')
            AND (DateTermed > '2013-11-01' OR DateTermed = '')
    ) AS Start,
    (
        SELECT DateTermed
        FROM CaseTable AS CaseTable_1
        WHERE (ReferralTable.ID = DemographicTable.ID_Number)
            AND (Date_Accepted <> '')
            AND (DateTermed > '2013-11-01' OR DateTermed = '')
    ) AS Term
FROM ReferralTable
INNER JOIN DemographicTable
    ON ReferralTable.ID = DemographicTable.ID_Number
    AND ReferralTable. Referral_date > '2012-12-01'
    AND ReferralTable. Code = 'JTC'
ORDER BY ReferralTable. Referral_date