我有两个表来存储地址,如下所示:
我想获取每个地址,城市,名称和地区名称(cityId,Areaid可能为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]
但这只会给我这个城市的名字。如何获得区域名称?
答案 0 :(得分: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]
答案 1 :(得分: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]
答案 2 :(得分: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)
答案 3 :(得分:0)
会在同一个表中添加另一个连接...这次加入区域ID工作? (其他答案因此而没有添加查询)
您可能希望将另一列添加到要为区域ID加入的位置,或者放入第三个表中,以便在可能的情况下删除多对多关系