第四章 中级SQL

join

与natural join不同的是,它的ID会出现两次
select * from student ,takes where student.ID = takes.ID;等价。

在这里插入图片描述

外连接

避免信息丢失
显示所有学生的列表,显示他们的ID,name,dept_name和tot_cred。
使用左外连接,这样保证了Snow学生出现在表中,那些只出现在takes关系模式中的属性上取空值。

select * from student natural left outer join takes;
等价于
select * from takes natural right outer join student;

在这里插入图片描述
全外连接的例子
显示‘Comp.Sci’系所有学生以及他们在2009年春季选修的所有课程段的列表。
2009年春季开设的所有课程段都必须显示,即使没有Comp.Sci系的学生选修这些课程段。

select * from(select * from student where dept_name = 'Comp. Sci.') natural full outer join (select * from takes where semester = 'Spring' and year = 2009);

视图:作为虚关系对用户可见的关系

最上层,作用:安全,简化

创建视图

列出Physics系在2009年秋季学期开设的所有课程段,以及每个课程段在哪栋建筑的哪个房间授课的信息。

create view physics_fall_2009 as select course.course_id,sec_id,building,room_number from course,section where course.course_id = section.course_id and course.dept_name = 'Physics' and section.semester = 'Fall' and section.year = 2009;

在这里插入图片描述

使用视图

在这里插入图片描述

视图更新 P72

在视图上进行插入,删除和更新会带来一些问题,可以很复杂.

事务

Commit work:提交当前事务,永久保存;
Rollback work:回滚当前事务,恢复执行该事务第一条语句之前的状态。

原子性:一个事务在完成所有步骤后提交其行为,或者在不能成功完成其所有动作的情况下回滚其所有动作。

完整性约束

create table中含有完整性约束的命令,not,null,unique,check

not null

name varchar(20) not null
budget numeric (12,2) not null

unique

unique(属性1,属性2,属性3....)
表示在属性1,2,3...上形成了一个超码

check子句

create table section
(semester varchar(6)
check(semester in ('Fall','Winter','Spring','Summer')));
模拟枚举类型

参照完整性p75

日期和时间 P78

date,time,timestamp

默认值

create table student
(ID varchar(5),
tot_cred numeric(3,0) default 0);

执行下列语句,该元组在tot_cred上的属性就被置为0.

insert into student(ID,name,dept_name)
values ('12345');

创建索引

create index student_ID_index on student(ID);

大对象类型

clob:字符数据的大对象数据类型
blob:二进制数据的大对象数据类型

声明属性
book_review clob (10KB)
image blob (10MB)

用户定义的类型 P80

授权

授予数据库用户Amit和Sally在department关系上的select权限:
grant select on department to Amit,Sally;
grant update (budget) on department to Amit,Sally;

收回权限:
revoke select on department from Amit,Sally;
revoke update (budget) on department from Amit,Sally;

角色 P83

create role instructor
grant select on takes to instructor

猜你喜欢

转载自blog.csdn.net/weixin_42882887/article/details/88600699
今日推荐