【数据库基础】用SQL语言关键字表示关系代数的交 并 差 内连接 外连接操作

来源:互联网 发布:如何编译linux源码 编辑:程序博客网 时间:2024/06/04 20:50

关系代数转换为SQL语言还存在着一个思维的转换。一般转换的过程如下:

SQL语言进行查询时用select….from…..where……
同时有多个条件约束时,用and or。其实本质上就是关系代数中的操作,select 就是关系代数中的投影,from后面跟着多个表名时,这些表就默认做笛卡尔积。where 后面的子句就是对表中的每一个元组进行筛选过滤,选出符合条件的元组,用到的and和or 对应关系代数中的交(intersect)和并(union)、。最后形成新表。

所以我们能不能直接用SQL语言更直接表达关系代数语句呢?
SQL提供了一些关键字来直接翻译关系代数语句。

如:求学过001号课程或者学过002号课程的同学的学号。

select S# from Sc where C#="001"unionselect S# from Sc where C#="002";

or

select S# from Scwhere C#="001" or C#="002";

如:既学过001号课程又学过002号课程的同学的学号。

select S# from Sc where C#="001"intersectselect S# from Sc where C#="002";

or

select S# from Sc where C#="001" and S# in (select S# from sc where C#="002");

eg:假定所有学生都有选课,求没学过002号课程的学生。

select distinct S# from Scexceptslect S# from Sc where C#="002";

or

select S# from Sc Sc1where not exists (select * from Sc SC2 where C#="002" and Sc.S#=Sc.S#);

有些低版本的DBMS不支持intersect 和expect

内链接:

为了方便,语法都按两个表连接写得。
1.θ连接
基本语法:

select 列名 [,[列名]……]from 表名1 inner join 表名2 {on 连接条件 | using (colname)(,{colname……})}}where 检索条件

2 自然连接

select 列名 [,[列名]……]from 表名1 natural join 表名2 where 检索条件

外连接

基本语法:

select 列名 [,[列名]……]from 表名1 {left outer|right outer|full outer} join 表名2 {on 连接条件 | using (colname)(,{colname……})}where 检索条件

eg:
这里写图片描述

阅读全文
0 0
原创粉丝点击