mysql中内连接,左连接和右连接的区别

来源:这里教程网 时间:2026-02-28 18:10:40 作者:

MySQL 中内连接、左连接和右连接的区别

内连接 (INNER JOIN)

只返回两个表中具有匹配行的记录。 匹配失败的记录将被丢弃。

左连接 (LEFT JOIN)

返回左表中的所有记录,即使右表中没有匹配的行。 右表中没有匹配行的记录将用 NULL 值填充。

右连接 (RIGHT JOIN)

返回右表中的所有记录,即使左表中没有匹配的行。 左表中没有匹配行的记录将用 NULL 值填充。

用法

内连接:用于查找两个表之间具有匹配行的记录,并丢弃不匹配的记录。 左连接:用于查找左表的所有记录,并包含右表中匹配行的记录。 右连接:用于查找右表的所有记录,并包含左表中匹配行的记录。

语法

内连接:

<code class="sql">SELECT *
FROM table1
INNER JOIN table2
ON table1.column1 = table2.column2;</code>

左连接:

<code class="sql">SELECT *
FROM table1
LEFT JOIN table2
ON table1.column1 = table2.column2;</code>

右连接:

<code class="sql">SELECT *
FROM table1
RIGHT JOIN table2
ON table1.column1 = table2.column2;</code>

例子

假设我们有以下两个表:

<code>Table1:
| id | name |
|---|---|
| 1 | John |
| 2 | Mary |
| 3 | Bob |
Table2:
| id | address |
|---|---|
| 1 | 123 Main St |
| 2 | 456 Elm St |
| 4 | 789 Oak St |</code>

内连接:

<code class="sql">SELECT *
FROM Table1
INNER JOIN Table2
ON Table1.id = Table2.id;</code>

结果:

id name address
1 John 123 Main St
2 Mary 456 Elm St

左连接:

<code class="sql">SELECT *
FROM Table1
LEFT JOIN Table2
ON Table1.id = Table2.id;</code>

结果:

id name address
1 John 123 Main St
2 Mary 456 Elm St
3 Bob NULL

右连接:

<code class="sql">SELECT *
FROM Table1
RIGHT JOIN Table2
ON Table1.id = Table2.id;</code>

结果:

id name address
1 John 123 Main St
2 Mary 456 Elm St
4 NULL 789 Oak St

相关推荐