JayT
JayT

Reputation: 107

SQL Select Data from Three Tables

I have a problem where I need to select data from three different tables, and format in a specify way. I have tried JOINS, UNIONS... and various select statements but cannot get the format the way I would like.

The Tables are as such :

Table 1 (Area Table)

ID  |Area 
----|----- 
 1  | England 
 2  | Wales 
 3  | Scotland  
 4  | Ireland 

Table 2 (Site Table)

 ID  |AreaID  |Site     
 --- |--------|-----    
 1   | 1      | London 
 2   | 1      | Bath  
 3   | 2      | Cardiff
 4   | 3      | Edinburgh

Table 3 (Location Table)

ID  |AreaID   |TownID     | Location    
--- |---------|-----------|-----   
 1  | 1       | 1         | Sussex 
 2  | 1       | 1         | Mitcham 
 3  | 2       | 2         | Canton

Now, I need to select the data from all three tables to produce the following :

AreaID  |AreaName   |SiteID     | SiteName   |  LocationID  | LocationName    
------- |-----------|-----------|---------- -|--------------|----------  
 1      | England   | 1         | London     | 1            | Sussex    
 1      | England   | 1         | London     | 2            | Mitcham   
 2      | Wales     | 3         | Cardiff    | 3            | Canton  
 3      | Scotland  | 3         | Edinburgh  | NULL         | NULL      
 4      | Ireland   | NULL      | NULL       | NULL         | NULL

So, basically, a Location Entry requires a Site entity, and a Site Entity requires an Area. But an Area does not require a Site, and a Site does not require a location.

Hope this makes sense.

If anyone could help, would be much appreciated.

Upvotes: 0

Views: 2132

Answers (1)

Bassam Mehanni
Bassam Mehanni

Reputation: 14944

This seems like a straight forward LEFT JOIN:

SELECT a.ID AS AreaID, a.Area AS AreaName, 
       s.ID AS SiteID, s.Site AS SiteName, 
       l.ID AS LocationID, l.Location AS LocationName
FROM Area a
     LEFT JOIN Site s ON s.AreaID = a.ID
     LEFT JOIN Location l ON l.AreaID = a.ID

Hope this helps

Upvotes: 5

Related Questions