Home >Database >Mysql Tutorial >Inner vs. Outer Joins: What's the Difference?

Inner vs. Outer Joins: What's the Difference?

Susan Sarandon
Susan SarandonOriginal
2025-01-25 17:47:11391browse

Inner vs. Outer Joins: What's the Difference?

In-depth understanding of the difference between inner joins and outer joins

The join statement is the core in database operations, which allows us to combine data from multiple tables based on specific conditions. It is crucial to understand the different types of joins, with inner joins and outer joins being two key categories.

The difference between inner join and outer join

Inner join only returns records that meet the join conditions. It is similar to the intersection of two sets, producing only elements that are present in both sets. An outer join, on the other hand, will return all records from one or both tables, even if they have no corresponding records in the other table. This is similar to the union of two sets, including common and unique elements in each set.

Variation of outer join

There are three main types of outer joins:

  • LEFT JOIN: Keeps all records from the left table (A) and includes matching records from the right table (B). Values ​​in B that do not match records will be assigned NULL.
  • RIGHT JOIN: Similar to LEFT JOIN, but gives priority to records from the right table (B). Values ​​in A that do not match records will be assigned NULL.
  • FULL JOIN: Combines all records from two tables (A and B). Records that do not have corresponding records in another table will be assigned the value NULL.

Example using a simple dataset

Consider the following form:

表 A 表 B
1 3
2 4
3 5
4 6

Inner connection:

<code class="language-sql">SELECT * FROM A INNER JOIN B ON A.a = B.b;</code>

Output:

a b
3 3
4 4

Left outer join:

<code class="language-sql">SELECT * FROM A LEFT JOIN B ON A.a = B.b;</code>

Output:

a b
1 NULL
2 NULL
3 3
4 4

Right outer join:

<code class="language-sql">SELECT * FROM A RIGHT JOIN B ON A.a = B.b;</code>

Output:

a b
3 3
4 4
NULL 5
NULL 6

Full outer join:

<code class="language-sql">SELECT * FROM A FULL OUTER JOIN B ON A.a = B.b;</code>

Output:

a b
1 NULL
2 NULL
3 3
4 4
NULL 5
NULL 6

By understanding the difference between inner and outer joins, developers can effectively manipulate data and extract meaningful relationships from multiple tables.

The above is the detailed content of Inner vs. Outer Joins: What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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