SQL笔记(四) 集合运算

集合运算

SQL作用的关系上的unionintersect、和 except 运算对应数学集合论中的- 运算

  • 在2009年秋季学期开设的所有课程的集合:
select course_id
from section
where semester = 'Fall' and year = 2009;
  • 在2010年春季学期开设的所有课程的集合:
select course_id
from section
where semester = 'Spring' and year = 2010;

使用c1和c2分别指代以上查询结果的两个关系。

并运算

查询1. 并运算

找出在2009年秋季学期开课,或者在2010年春季学期开课或两个学期都开课的所有课程:

(select course_id
from section
where semester = 'Fall' and year = 2009)
union
(select course_id
from section
where semester = 'Spring' and year = 2010);

union运算自动去除重复
使用union all代替union 可以保留重复

交运算

查询2. 交运算

找出2009年秋季和2010年春季同时开课的所有课程的集合:

(select course_id
from section
where semester = 'Fall' and year = 2009)
intersect
(select course_id
from section
where semester = 'Spring' and year = 2010);

intersect运算自动去除重复
使用intersect all代替intersect 可以保留重复

差运算

某些SQL实现,特别是Oracle,使用关键字minus代替except。

查询3. 差运算

找出在2009年秋季开课,但不在2010年春季学期开课的所有课程:

(select course_id
from section
where semester = 'Fall' and year = 2009)
except
(select course_id
from section
where semester = 'Spring' and year = 2010);

except运算自动去除重复
使用except all代替except 可以保留重复

猜你喜欢

转载自blog.csdn.net/u010327460/article/details/80486356