Search code examples
mysqlsqlinner-joinjoin

How to write SQL query using a join on 3 tables?


I have created a hypothetical scenario with some dummy data. Below are 3 basic tables and I'm looking to write a query to find what property/properties Mary has viewed. In this scenario Mary has viewed 1 property a flat in Glasgow.

Table 1: Client

=====================
ID  Name        
=====================
5   Tom
6   Mary
7   John

Table 2: Property

=====================
ID  CITY        TYPE    
=====================
14  Aberdeen    House
16  Glasgow     Flat
21  Glasgow     House
94  London      Flat

Table 3: Viewing

========================
Client  Property    Date    
========================
5       14      01-12-2016
5       21      08-12-2016
6       16      10-10-2016

Solution

  • Definitely use inner joins for this, a quick example of this could be

    SELECT c.Name, p.Type, p.City, v.Date
    FROM Viewing v 
    JOIN Client c ON v.client = c.ID
    JOIN Property p ON v.property = p.ID
    WHERE c.Name = 'Mary'
    

    That should show you who view what and when. I've used aliases on the table names just to keep it neat.