1、集合:
集合在数据库领域表示记录的集合,用来进行集合运算的运算符称为集合运算符
2、表的加法:union
product1:
product2:
加法运算:
select product_id, product_name
from product1
union
select product_id, product_name
from product2;
运算结果:
+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 0001 | T恤衫 |
| 0002 | 打孔器 |
| 0003 | 运动T恤 |
| 0004 | 菜刀 |
| 0005 | 高压锅 |
| 0006 | 叉子 |
| 0007 | 擦菜板 |
| 0008 | 圆珠笔 |
| 0009 | 手套 |
| 0010 | 水壶 |
+------------+--------------+
注意:
- union等集合运算符通常都会除去重复的记录。
- 作为运算对象的记录的列数必须相同
- 作为运算对象的记录中列的类型必须一致
- 通过union进行并集运算时可以使用任何形式的select语句,之前学过的where、group by、having等子句都可以使用。但order by只能在最后使用,且只能使用一次。
3、包含重复行的集合运算——all选项
select product_id, product_name
from product1
union all
select product_id, product_name
from product2;
运算结果:
+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 0001 | T恤衫 |
| 0002 | 打孔器 |
| 0003 | 运动T恤 |
| 0004 | 菜刀 |
| 0005 | 高压锅 |
| 0006 | 叉子 |
| 0007 | 擦菜板 |
| 0008 | 圆珠笔 |
| 0001 | T恤衫 |
| 0002 | 打孔器 |
| 0003 | 运动T恤 |
| 0009 | 手套 |
| 0010 | 水壶 |
+------------+--------------+
4、选取表中公共部分:intersect(MySQL不支持)
select product_id, product_name
from product1
intersect
select product_id, product_name
from product2
运算结果:
+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 0001 | T恤衫 |
| 0002 | 打孔器 |
| 0003 | 运动T恤 |
+------------+--------------+
5、记录的减法:except(Oracle、MySQL不支持)
select product_id, product_name
from product1
intersect
select product_id, product_name
from product2
结果显示为product1中记录减去product2表中记录,剩余的记录。