首页  >  文章  >  数据库  >  mysql中内连接,左连接和右连接的区别

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

下次还敢
下次还敢原创
2024-04-29 04:00:36613浏览

MySQL 中内连接、左连接和右连接的区别在于:内连接只返回同时在两个表中匹配的行,而左连接返回左表所有行,包含匹配右表行,右连接返回右表所有行,包含匹配左表行。内连接语法:SELECT * FROM table1 INNER JOIN table2 ON table1.column1 = table2.column2;左连接语法:SELECT * FROM table1 LEFT JOIN table2 ON table1.column1 = table2.column2;右连接语法:SELE

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

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

以上是mysql中内连接,左连接和右连接的区别的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn