一、定義數據表
1、建立一個 “學生” 表 student。
create table student
(Sno char(9) primary key,/*主鍵(主碼),列級完整性約束條件*/
Sname char(20) unique,/*Sname 取唯一值*/
Ssex char(2),
Sage smallint,
Sdep char(20)
);
2、建立一個 “課程” 表 course。
create table course
(Cno char(4) primary key,/*Cno主鍵*/
Cname char(40) not null,/*Cname不能取空值*/
Cpno char(4),/*先修課*/
Ccredit smallint,
foreign key(Cpno) references course(Cno)/*Cpno是外鍵,對應course的Cno*/
);
3、建立學生課程表 sc。
create table sc
(Sno char(9),
Cno char(4),
Grade smallint,
primary key(Sno,Cno),/*主碼由兩個屬性構成*/
foreign key(Sno) references student(Sno),
foreign key(Cno) references course(Cno)
);
二、數據類型
數據類型 含義
char(n),character(n) 長度為n的定長字符串
varchar(n),charactervarying(n) 最大長度為n的變長字符串
clob 字符串大對象
blob 二進制大對象
int,integer 長整數(4字節)
smallint 短整數(2字節)
bigint 大整數(8字節)
numeric(p,d) 定點數,有p位數字組成,小數點后面有d位數字
decimal 同numeric
boolean 布爾值
date 日期,包含年月日,格式為YYYY-MM-DD
time 時間,包含一日的時分秒,格式為HH:MM:SS
timestamp 時間戳類型
interval 時間間隔類型
三、模式與表
方法:在表明中明顯的給出模式名。
create table "S-T".student(···);
create table "S-T".course(···);
create table "S-T".sc(···);
四、修改基本表
【例】向 student 表增加 “入學時間” 列,其數據類型為日期型
alter table student add S_entrance date;
【例】修改 student 表的 Sage 字段默認值為 20
alter table student alter column Sage set default 20; /*修改student表的Sage字段的默認值為20*/
【例】將 student 表的 Sage 由字符型改為整型。
alter table student modify column Sage int;
【例】增加課程名必須取唯一的約束條件。
alter table course add unique(Cname);
五、刪除基本表
若選擇 restrict , 則該表的刪除是有限制的,欲刪除的基本表不能被刪除。
若選擇 cascade,則刪除沒有限制,在刪除表的同時,相關依賴對象,例如視圖,都將被一起刪除。
drop table student restrict|cascade;