1

I have two tables to store addresses as follows:enter image description here

I want to get every address, city, name and area name (cityId,Areaid maybe null)

I tried:

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

but that will give me only the names of the city. How to get the area name, too?

contradictioned
  • 1,253
  • 2
  • 14
  • 26
Alaa Jabre
  • 1,843
  • 5
  • 26
  • 52

4 Answers4

3

You need to join twice with the Places table. Once for the cities and once for the Areas.

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] 
Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
3

Add another join

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] 
juergen d
  • 201,996
  • 37
  • 293
  • 362
0

Try This

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)
Miller
  • 1,096
  • 9
  • 22
0

will adding another join to the same table ... this time joining for the area id work? (other answers dropped in so not adding the query)

you may want to add another column to places to join for the area id or drop in a third a table to get rid of the many to many relationships if possible

user1023993
  • 151
  • 1
  • 4
  • 13