In-depth understanding of SQL JOIN: detailed explanation of INNER, LEFT, RIGHT and FULL JOIN
SQL JOIN is a core operation in data retrieval, allowing us to combine rows from multiple tables based on common fields. In MySQL, there are several JOIN types to choose from, each providing a specific way of handling matching and unmatched rows.
Differences between different SQL JOIN types
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
Actual case
Consider the following example table:
<code>表A: | id | firstName | lastName | |---|---|---| | 1 | Arun | Prasanth | | 2 | Ann | Antony | | 3 | Sruthy | Abc | | 6 | New | Abc | 表B: | id2 | age | place | |---|---|---| | 1 | 24 | Kerala | | 2 | 24 | Usa | | 3 | 25 | Ekm | | 5 | 24 | Chennai |</code>
INNER JOIN:
<code>SELECT * FROM 表A INNER JOIN 表B ON 表A.id = 表B.id2;</code>
Result:
firstName | lastName | age | place |
---|---|---|---|
Arun | Prasanth | 24 | Kerala |
Ann | Antony | 24 | Usa |
Sruthy | Abc | 25 | Ekm |
LEFT JOIN:
<code>SELECT * FROM 表A LEFT JOIN 表B ON 表A.id = 表B.id2;</code>
Result:
firstName | lastName | age | place |
---|---|---|---|
Arun | Prasanth | 24 | Kerala |
Ann | Antony | 24 | Usa |
Sruthy | Abc | 25 | Ekm |
New | Abc | NULL | NULL |
RIGHT JOIN:
<code>SELECT * FROM 表A RIGHT JOIN 表B ON 表A.id = 表B.id2;</code>
Result:
firstName | lastName | age | place |
---|---|---|---|
Arun | Prasanth | 24 | Kerala |
Ann | Antony | 24 | Usa |
Sruthy | Abc | 25 | Ekm |
NULL | NULL | 24 | Chennai |
Full Join:
<code>表A: | id | firstName | lastName | |---|---|---| | 1 | Arun | Prasanth | | 2 | Ann | Antony | | 3 | Sruthy | Abc | | 6 | New | Abc | 表B: | id2 | age | place | |---|---|---| | 1 | 24 | Kerala | | 2 | 24 | Usa | | 3 | 25 | Ekm | | 5 | 24 | Chennai |</code>
The above is the detailed content of How Do INNER, LEFT, RIGHT, and FULL JOINs Differ in SQL?. For more information, please follow other related articles on the PHP Chinese website!