← 返回首页
MySQ基础教程(十二)
发表时间:2020-03-17 02:47:15
讲解MySQL的关系代数

关系代数是一种抽象的查询语言,它用对关系的运算来表达查询。

任何一种运算都是将一定的运算符作用于一定的运算对象上,得到预期的结果。所以运算对象、运算符、运算结果是运算的三大要素。

按运算符的不同分为传统的集合运算和专门的关系运算两类: 传统的集合运算包括:并(∪)、差(−)、交(∩)、笛卡尔积(×)。 专门的关系运算包括:选择(σ)、投影(π)、连接(⋈)、除运算(÷)。

添加三张测试表和初始化数据:

#学生表
create table students(
   sid int not null auto_increment primary key,
   sname varchar(20) 
);
#学生临时表
create table students_temp(
   sid int not null auto_increment primary key,
   sname varchar(20) 
);
#课程表
create table course(
   cid varchar(4) not null primary key,
   cname varchar(20)
);
#初始化测试数据
insert into students (sname) values ('张三'),('李四'),('王五');
insert into students_temp (sname) values ('张三'),('lisi'),('wangwu');
insert into course (cid,cname) values ('C001','Java'),('C002','Html'),('C003','MySQL');

1.并(union)

假设有关系R和S,则R和S的并结果如下:

SQL代码验证如下:

#students与students_temp的并
select *  from students union all select * from students_temp ;
#students与students_temp的并(去除重复记录)
select *  from students union select * from students_temp ;

2.差(except)

假设有关系R和S,则R和S的差结果如下: SQL代码验证如下:

#students与students_temp的差
select * from (select distinct * from students union all select distinct * from students_temp) as A where not exists (select * from students_temp where A.sid=sid and A.sname = sname);

3.交(intersection) 假设有关系R和S,则R和S的交结果如下:

SQL代码验证如下:

#students与students_temp的交
select * from (select distinct * from students union all select distinct * from students_temp) as R_S group by sid,sname having count(*)>1;

4.笛卡尔积(cartesian product)

假设有关系R和S,则R和S的笛卡尔积结果如下:

SQL代码验证如下:

#students与course的笛卡尔积
select * from students,course;
select * from course,students;

5.投影(projection)

关系R上的投影是从R中选择出若干属性列组成新的关系。 SQL代码验证如下:

#students在sname字段上的投影
select sname from students;

6.选择(selection)

在关系R中选择满足给定条件的记录。 SQL代码验证如下:

#students在sname字段上先投影再选择
select sname from students where sid = 1;

剩下的连接部分,我们将在后面的多表连接中详细讲解。