Join 3 tables (or more) syntax
SELECT t1.column_1, t2.column_2, t3. column_3..., tx.column_x FROM table_1 t1, table_2 t2, table_3 t3, ..., table_x tx WHERE t1.column_1 = t2.column_2 AND t2.column_2 = t3.column_3 ... AND t(x-1).column_(x-1) = tx.column_x;
Ofcourse, there is no need to keep column’s indexes ordered like in the syntax above. They just have to store the same type’s of values to match to each other in the same way we used it with basic JOIN statement.
Let’s take a closer look at the sample tables: PILOTS, AIRCRAFTS and AIRPORTS.
SELECT * FROM pilots;
name | location |
---|---|
Jack | Los Angeles |
Thomas | Berlin |
Rick | London |
John | Paris |
SELECT * FROM aircrafts;
aircraft | location |
---|---|
cirrus | Paris |
LancAir | Los Angeles |
cessna 172 | Berlin |
cessna 152 | London |
SELECT * FROM airports;
airport | location | fuel_station |
---|---|---|
Heathrow | London | yes |
Charles Degaulle | Paris | no |
Tempelhof | Berlin | no |
Los Angeles | Los Angeles | yes |
in this case, each table has a common collumn “location”. This is our key for joining tables.
We are looking for the plane and pilot who works at specific airport which has a fuel station.
SELECT name, aircraft, pilots.location, fuel_station FROM pilots, aircrafts, airports WHERE pilots.location = aircrafts.location AND aircrafts.location = airports.location AND fuel_station = 'yes';
name | aircraft | location | fuel_station |
---|---|---|---|
Rick | cessna 152 | London | yes |
Jack | LancAir | Los Angeles | yes |
Download MySQL sample database dump here.
The post How to JOIN 3 tables or more appeared first on Programmer's lounge.