第10讲:利用SQL语言实现关系代数操作

一、实现并、交、差运算

1. 基本语法形式:子查询 [union [all] | intersect [all] | except [all] 子查询]

    ①意义:将关系代数中的∪、∩、- 分别用union、intersect、except来代替

    ②不带all:删除重复的元组

    ③带all:保留重复的元组

【示例】假设子查询1的一个元组出现m次,子查询2的一个元组出现n次,则该元组在:

  • 子查询1 union all 子查询2        // 出现m+n次
  • 子查询1 intersect all 子查询2   // 出现min(m,n)次
  • 子查询1 except all 子查询2      // 出现max(0, m-n)次

2. SQL并运算

【示例1】求学过002号课的同学或学过003号课的学生的学号:

  • select S# from SC where C# = '002' union select S# from SC where C# = '003';
  • select S# from SC where C# = '002' or C# = '003';

【示例2】已知两个表Customers(CID, Cname, City, Discnt)和Agents(AID, Aname, City, Percent)求客户所在的或者代理商所在的城市:

  • select City from Customers union select City from Agents;

3. SQL交运算

    ①intersect运算符并未增强SQL的表达能力,即没有intersect,SQL也可以通过其他方式表达相同的查询需求

    ②但intersect更方便表达查询需求,同时也增加了SQL语言的不唯一性

【示例】求既学过002号课,又学过003号课的学生的学号:

  • select S# from SC where C# = '002' intersect select S# from SC where C# = '003';
  • select S# from SC where C# = '002' and S# in (select S# from SC where C# = '003');

4. SQL差运算

    ①except运算符也未增强SQL的表达能力,即没有except,SQL也可以通过其他方式表达相同的查询需求

    ②但except更方便表达查询需求,同时也增加了SQL语言的不唯一性

【示例】假定所有学生都有选课,求没学过002号课程的学生的学号:

  • select DISTINCT S# from SC except select S# from SC where C# = '002';  // 所有学生 减掉 学过002号课的学生
  • select DISTINCT S# from SC SC1 where not exists (select * from SC where C# = '002' and S# = SC1.S#);

猜你喜欢

转载自www.cnblogs.com/xzxl/p/10743450.html