结构化查询语言之 SQL 集合运算(以Mysql为例)

185 阅读2分钟

@[TOC] 查询使用的数据库文件下载


  SQL 作用在关系上的union、intersect、except运算对应于数学集合论中的 \cup、\cap、- 运算。但是,mysql无intersect、except

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
    );
    

  与select子句不同,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
    );
    

  与select子句不同,intersect运算自动去除重复,如果我们想保留所有重复,就必须用intersect all代替intersect

  mysql无intersect操作符,但可以使用in来实现交运算:

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

在这里插入图片描述

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;   注:mysql无except操作符,但可以使用not in来实现交运算:

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

在这里插入图片描述


References: [1] Abraham Silberschatz, Henry F Korth, S Sudarshan. Database System Concepts. New York: McGraw-Hill, 2010 Database System Concepts