SQL Inner join more than two tables

Ben Pearce picture Ben Pearce · Feb 21, 2013 · Viewed 336.6k times · Source

I can currently query the join of two tables on the equality of a foreign/primary key in the following way.

 $result = mysql_query("SELECT * FROM `table1` 
                         INNER JOIN 
                       `table2` ON table1.primaryKey=table2.table1Id");

I'd like to extend this to multiple tables (all with the same foreign keys). I am trying the following code which is not returning anything. Can anyone point out what I'm doing wrong?

 $result = mysql_query("SELECT * FROM `table1` 
                        INNER JOIN `table2` 
                        INNER JOIN table3 
                        ON table1.primaryKey=table2.table1Id=table3.table1Id");

Answer

Alex picture Alex · Feb 21, 2013
SELECT * 
FROM table1 
INNER JOIN table2
      ON table1.primaryKey=table2.table1Id
INNER JOIN table3
      ON table1.primaryKey=table3.table1Id