2011-09-05 130 views
3

我有一個帶有三個表的SQL Server數據庫:Gang,GangMember和Neighborhood。這些表的結構是這樣的:SQL - 使用左連接混合內連接

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] 

因爲幫派可能沒有鄰居,我不知道如何完成這個查詢。有人可以幫我嗎?謝謝!

+0

我覺得你有你的模型的一些更新異常等問題。我不認爲你已經正確定義了一個幫派成員,例如「幫派成員屬於(是的,他們可以屬於多個)」似乎是矛盾的。也許你的意思是說,同一個人*可以是同一個幫派的成員?如果是這樣,大概他們可以在不同的幫派中以不同的名字(或相同的名字)知道他們自己的保護。瞭解幫派之間的競爭傳統和他們的反建立性質,我很難想象哪個代理機構會是團伙成員ID的可信賴來源! – onedaywhen

+0

澄清:我認爲你的'GangMember'表需要分成兩個表格:一個用於模擬人(可能有諸如法定名稱,指紋,DNA等標識符),另一個用於建模人和她的幫派(難以想象任何標識符,而不是'已知'的名字)。 – onedaywhen

回答

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
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 
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 
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