天天看點

第四章 中級SQL

join

與natural join不同的是,它的ID會出現兩次

select * from student ,takes where student.ID = takes.ID;

等價。

第四章 中級SQL

外連接配接

避免資訊丢失

顯示所有學生的清單,顯示他們的ID,name,dept_name和tot_cred。

使用左外連接配接,這樣保證了Snow學生出現在表中,那些隻出現在takes關系模式中的屬性上取空值。

select * from student natural left outer join takes;
等價于
select * from takes natural right outer join student;
           
第四章 中級SQL

全外連接配接的例子

顯示‘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;
           
第四章 中級SQL

使用視圖

第四章 中級SQL

視圖更新 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
           

繼續閱讀