数据库的各种连接
分类
数据库中常见的连接方式有三种:
内连接(inner join)
外连接(outer join)
交叉连接(cross join)
外连接又分为左外连接(left outer join)、右外连接(right outer join)和全外连接(full outer join)
例子
假设我们有两个表 A 和 B,它们分别包含以下数据:
表 A: 表 B:
+---+ +---+
| a | | b |
+---+ +---+
| 1 | | 2 |
| 2 | | 3 |
| 3 | | 4 |
+---+ +---+
- 内连接(inner join)返回两个表中匹配的行:
SELECT * FROM A INNER JOIN B ON A.a = B.b;
结果:
+---+---+
| a | b
+---+---+
| 2 | 2 |
| 3 | 3 |
+---+---+
- 左外连接(left outer join)返回左表中的所有行,即使在右表中没有匹配的行:
SELECT * FROM A LEFT OUTER JOIN B ON A.a = B.b;
结果:
+------+------+
| a | b |
+------+------+
| 1 | NULL |
| 2 | 2 |
| 3 | 3 |
+------+------+
- 右外连接(right outer join)返回右表中的所有行,即使在左表中没有匹配的行:
SELECT * FROM A RIGHT OUTER JOIN B ON A.a = B.b;
结果:
+------+------+
| a | b |
+------+------+
| NULL | 4 |
| 2 | 2 |
| 3 | 3 |
+------+------+
- 全外连接(full outer join)返回两个表中的所有行,即使在另一个表中没有匹配的行。请注意,MySQL 不支持全外连接,但可以通过组合左外连接和右外连接来实现:
SELECT * FROM A LEFT OUTER JOIN B ON A.a = B.b
UNION
SELECT * FROM A RIGHT OUTER JOIN B ON A.a = B.b;
结果:
+------+------+
| a | b |
+------+------+
| NULL | 4 |
| 1 | NULL |
| 2 | 2 |
| 3 | 3 |
+------+------+
交叉连接(cross join)返回两个表的笛卡尔积,即返回两个表中所有可能的行组合。
SELECT * FROM A CROSS JOIN B;
结果:
+---+---+
| a | b |
+---+---+
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 2 |
| 2 | 3 |
| 2 | 4 |
| 3 | 2 |
| 3 | 3 |
| 3 | 4 |
+---+---+
#mysql(2)评论