2013-08-05 48 views
1

我有兩個表來存儲地址如下之間的連接:兩個兩個表

SELECT [Details] 
     ,[AddressId] 
     ,[CityId] 
     ,[PlaceName] as CityName 
     ,[AreaId] 
     ,[PlaceName] as AreaName 
    FROM [MyDB].[dbo].[Address] LEFT OUTER JOIN [MyDB].[dbo].[Places] 
    ON [CityId] = [PlaceI] 

但這隻會給我城市的名字。如何獲得地區名稱?

回答

3

您需要連接兩次Places表。一次爲城市,一次爲地區。

SELECT [Details] 
     ,[AddressId] 
     ,[CityId] 
     ,C.[PlaceName] as CityName 
     ,[AreaId] 
     ,A.[PlaceName] as AreaName 
FROM [MyDB].[dbo].[Address] 
    LEFT OUTER JOIN [MyDB].[dbo].[Places] C 
     ON [CityId] = C.[PlaceI] 
    LEFT OUTER JOIN [MyDB].[dbo].[Places] A 
     ON [AreaId] = A.[PlaceI] 
3

添加另一個加盟

SELECT [Details] 
     ,[AddressId] 
     ,[CityId] 
     ,p1.[PlaceName] as CityName 
     ,[AreaId] 
     ,p2.[PlaceName] as AreaName 
    FROM [MyDB].[dbo].[Address] 
    LEFT OUTER JOIN [MyDB].[dbo].[Places] p1 ON [CityId] = p1.[PlaceId] 
    LEFT OUTER JOIN [MyDB].[dbo].[Places] p2 ON [AreaId] = p2.[PlaceId] 
+3

你有兩次完全相同的連接條件。一個應該加入'AreaId' –

+0

當然。謝謝。 –

0

嘗試這個

SELECT [Details] 
     ,[AddressId] 
     ,[CityId] 
     ,C.[PlaceName] as CityName 
     ,[AreaId] 
     ,A.[PlaceName] as AreaName 
FROM [MyDB].[dbo].[Address] 
    INNER JOIN [MyDB].[dbo].[Places] C 
    ON ([CityId] = [PlaceID] AND IsCity=1) 
    OR ([AreaId] = [PlaceID] AND IsCity=0) 
0

將增加另外加入到同一個表......這個時候加入區域ID的工作? (其他答案在不添加查詢的情況下下降)

您可能想要添加另一列以加入區域ID或放置在第三個表格中以便儘可能地去除多對多關係