Joining Multiple Tables Using Inner Join in SQL
When working with relational databases, it is often necessary to combine data from multiple tables based on common fields. Inner join is a fundamental SQL operation that allows you to achieve this by creating a new result set containing matching rows from two or more tables.
To inner join two tables, you use the following syntax:
SELECT * FROM table1 INNER JOIN table2 ON table1.common_field = table2.common_field
In this example, table1 and table2 are the tables being joined, and common_field is the field on which the tables are matched.
Joining More Than Two Tables
The syntax above can be extended to join multiple tables using multiple inner joins. However, it is important to note that the tables must have at least one common field for the join to work correctly.
To inner join three tables, you would use the following syntax:
SELECT * FROM table1 INNER JOIN table2 ON table1.common_field = table2.common_field INNER JOIN table3 ON table1.common_field = table3.common_field
In this example, table1, table2, and table3 are the tables being joined, and common_field is the field that is shared among all three tables.
Example
Consider the following tables:
To join these three tables and retrieve all data for a specific primary key value, you would use the following query:
SELECT * FROM table1 INNER JOIN table2 ON table1.primaryKey = table2.table1Id INNER JOIN table3 ON table1.primaryKey = table3.table1Id WHERE table1.primaryKey = 5;
This query will return a result set containing the rows from table1, table2, and table3 that have a common primaryKey value of 5.
The above is the detailed content of How Do I Use SQL's INNER JOIN to Combine Data from Multiple Tables?. For more information, please follow other related articles on the PHP Chinese website!