深入理解SQL JOIN:INNER、LEFT、RIGHT和FULL JOIN详解
SQL JOIN是数据检索中的核心操作,允许我们基于公共字段组合多个表中的行。在MySQL中,有多种JOIN类型可供选择,每种类型都提供了一种特定方式来处理匹配和不匹配的行。
不同SQL JOIN类型的区别
INNER JOIN
LEFT JOIN
RIGHT JOIN
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>
INNER JOIN:
<code>SELECT * FROM 表A INNER JOIN 表B ON 表A.id = 表B.id2;</code>
结果:
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>
结果:
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>
结果:
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>
结果:
firstName | lastName | age | place |
---|---|---|---|
Arun | Prasanth | 24 | Kerala |
Ann | Antony | 24 | Usa |
Sruthy | Abc | 25 | Ekm |
New | Abc | NULL | NULL |
NULL | NULL | 24 | Chennai |
以上是内部,左,右和完整连接在SQL上有何不同?的详细内容。更多信息请关注PHP中文网其他相关文章!