数据库系统概念笔记- 2 连接类型

常见连接类型指如下:

  • 自然连接(内连接)
  • 左外连接
  • 右外连接
  • 全连接

示例数据:
比如如下的数据库, 一个是prices表存储每个产品的名字和加个. 另外一个是nums表存储每个产品的名字和个数.

create table prices (product varchar(32), price int);
create table nums (product varchar(32), num int);
insert into prices values ("apple", 12), ("kiwis", 13), ("melons", 15);
insert into nums values ("apple", 2), ("kiwis", 1), ("pea", 5), ("strawberry", 12);
mysql> select * from prices;
+---------+-------+
| product | price |
+---------+-------+
| apple   |    12 |
| kiwis   |    13 |
| melons  |    15 |
+---------+-------+
4 rows in set (0.00 sec)

mysql> select * from nums;
+------------+------+
| product    | num  |
+------------+------+
| apple      |    2 |
| kiwis      |    1 |
| pea        |    5 |
| strawberry |   12 |
+------------+------+
4 rows in set (0.00 sec)

自然连接:

只选择公共值相同的元组:
自然连接

mysql> select * from prices join nums using (product);
+---------+-------+------+
| product | price | num  |
+---------+-------+------+
| apple   |    12 |    2 |
| kiwis   |    13 |    1 |
+---------+-------+------+
3 rows in set (0.00 sec)

左外连接

保留左边元组:
在这里插入图片描述

mysql> select * from prices left outer join nums using (product);
+---------+-------+------+
| product | price | num  |
+---------+-------+------+
| apple   |    12 |    2 |
| kiwis   |    13 |    1 |
| melons  |    15 | NULL |
+---------+-------+------+
3 rows in set (0.00 sec)

右外连接

保留外侧连接:
在这里插入图片描述

mysql> select * from prices right outer join nums using (product);
+------------+------+-------+
| product    | num  | price |
+------------+------+-------+
| apple      |    2 |    12 |
| kiwis      |    1 |    13 |
| pea        |    5 |  NULL |
| strawberry |   12 |  NULL |
+------------+------+-------+

全连接

保留两侧连接
在这里插入图片描述
mysql不支持

select prices.*, nums.* from prices full outer join nums on prices.product=nums.product;

所以我们可以用left join + union + right join

mysql> select * from prices left join nums using (product) union select * from prices right join nums using (product);
+------------+-------+------+
| product    | price | num  |
+------------+-------+------+
| apple      |    12 |    2 |
| kiwis      |    13 |    1 |
| apple      |     2 |   12 |
| melons     |    15 | NULL |
| kiwis      |     1 |   13 |
| pea        |     5 | NULL |
| strawberry |    12 | NULL |
+------------+-------+------+
7 rows in set (0.00 sec)

目录:
数据库系统概念笔记

猜你喜欢

转载自blog.csdn.net/scugxl/article/details/97896353
今日推荐