集合运算
- 集合运算
- 并运算
-
-
- 查询1. 并运算
-
-
- 交运算
-
-
- 查询2. 交运算
-
-
- 差运算
-
-
- 查询3. 差运算
-
-
- 并运算
SQL作用的关系上的
union
、
intersect
、和
except
运算对应数学集合论中的
∪
、
∩
、
-
运算
- 在2009年秋季学期开设的所有课程的集合:
select course_id
from section
where semester = 'Fall' and year = ;
- 在2010年春季学期开设的所有课程的集合:
select course_id
from section
where semester = 'Spring' and year = ;
使用c1和c2分别指代以上查询结果的两个关系。
并运算
查询1. 并运算
找出在2009年秋季学期开课,或者在2010年春季学期开课或两个学期都开课的所有课程:
(select course_id
from section
where semester = 'Fall' and year = )
union
(select course_id
from section
where semester = 'Spring' and year = );
union
运算自动去除重复
使用
代替
union all
可以保留重复
union
交运算
查询2. 交运算
找出2009年秋季和2010年春季同时开课的所有课程的集合:
(select course_id
from section
where semester = 'Fall' and year = )
intersect
(select course_id
from section
where semester = 'Spring' and year = );
intersect
运算自动去除重复
使用
代替
intersect all
可以保留重复
intersect
差运算
某些SQL实现,特别是Oracle,使用关键字minus代替except。
查询3. 差运算
找出在2009年秋季开课,但不在2010年春季学期开课的所有课程:
(select course_id
from section
where semester = 'Fall' and year = )
except
(select course_id
from section
where semester = 'Spring' and year = );
except
运算自动去除重复
使用
代替
except all
可以保留重复
except