Home > Database > Mysql Tutorial > How Do I Use SQL's INNER JOIN to Combine Data from Multiple Tables?

How Do I Use SQL's INNER JOIN to Combine Data from Multiple Tables?

Barbara Streisand
Release: 2025-01-01 01:48:09
Original
567 people have browsed it

How Do I Use SQL's INNER JOIN to Combine Data from Multiple Tables?

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
Copy after login

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
Copy after login

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:

  • table1 contains rows with primaryKey, name, and age fields.
  • table2 contains rows with table1Id, address, and phone_number fields.
  • table3 contains rows with table1Id, occupation, and income fields.

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template