Joining Multiple Tables Using SQL Inner JOIN
When working with relational databases, it is often necessary to combine data from multiple tables. SQL provides the INNER JOIN operator for this purpose.
To perform an inner join on two tables, you specify the equality condition between their primary and foreign keys. For example:
SELECT * FROM table1 INNER JOIN table2 ON table1.primaryKey = table2.table1Id;
This query will return all rows from both tables that have matching primary and foreign keys.
To extend this to multiple tables, simply add additional INNER JOIN clauses to the query, using the same foreign/primary key equality condition. However, the following code is not returning any results:
SELECT * FROM table1 INNER JOIN table2 INNER JOIN table3 ON table1.primaryKey = table2.table1Id = table3.table1Id;
The reason for this is that the equality condition must be specified separately for each table. The correct syntax is:
SELECT * FROM table1 INNER JOIN table2 ON table1.primaryKey = table2.table1Id INNER JOIN table3 ON table1.primaryKey = table3.table1Id;
This query will return all rows from table1 that have matching primary and foreign keys in table2 and table3.
The above is the detailed content of Why Doesn't My SQL INNER JOIN With Multiple Tables Return Any Results?. For more information, please follow other related articles on the PHP Chinese website!