1

我有两个表来存储地址,如下所示:在此处输入图像描述

我想获取每个地址、城市、名称和地区名称(cityId,Areaaid 可能为 null)

我试过了:

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

但这只会给我城市的名字。如何获得区域名称呢?

4

4 回答 4

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] 
于 2013-08-05T12:37:43.877 回答
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] 
于 2013-08-05T12:37:54.683 回答
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)
于 2013-08-05T12:40:53.730 回答
0

将在同一个表中添加另一个连接......这次加入区域 ID 工作?(其他答案已删除,因此不添加查询)

如果可能,您可能希望在地方添加另一列以加入区域 id 或放入第三个表以摆脱多对多关系

于 2013-08-05T12:42:24.833 回答