基本表的定义:
创建了一个模式就建立了一个数据库的命名空间,一个框架。在这个空间中首先要定义的是该模式包含的数据库基本表。
数据类型:
每一个属性来自一个域,它的取值必须在域中的值。
常用的:
char(n) 字符串
int 整数(4字节)
smallint 短整数(2字节)
float 浮点数
date 日期 :yyyy-mm-dd
time 时间 :hh:mm:ss
char不能做算术运算,date可以算术运算。
基本格式:
create table <表名>
(
<列表> <数据类型> [列级完整性约束条件]
[,<列表> <数据类型> [列级完整性约束条件]]
...
[,<表级完整性约束条件>]
);
建表的同时还可以定义与该表有关的完整性约束条件。
实例:
1.建立一个学生表
create table student
(
Sno char(9) primary key, /* 主码*/
Sname char(20) unique, /*取唯一值 */
Ssex char(2),
Sage smallint,
Sdept char(20)
);
2.建立一个课程表Course
create table Course
(
Cno char(4) primary key,
Cname char(40) not null,
Cpno char(4),
Ccredit smallint,
foreign key (Cpno) references Course(Cno)
);
参照表和被参照表可以是同一表。
模式和表:
定义一个表的模式的三种方法:
1:在表名中明显的给出模式名:
create table <"模式名".表名>(...);
--如:
create table "test".student
(
Sno char(9) primary key, /* 主码*/
Sname char(20) unique, /*取唯一值 */
Ssex char(2),
Sage smallint,
Sdept char(20)
);
2. 在创建模式时创建表
create schema test authorization u1
create table student
(
sno char(9) primary key,
cno char(5) not null,
age int
);
3.如果没有按上面定义,关系数据库管理系统 会使用模式列表中第一个存在的模式作为数据库对象的模式名。
修改表:
一般格式:
alter table <表名>
add <列名><数据类型>[完整性约束]
add<表级完整性约束>
drop <列名>[cascade|restrict]
drop constraint<完整性约束名> [restrict|cascade]
alter column <列名><数据类型
举例:添加“入学时间”
alter table student
add 入学时间 date;
修改年龄为int 型
alter table student
alter column 年龄 int
删除“入学时间"这一列
alter table student
drop 入学时间;
删除表:
一般格式:
drop table <表名> [restrict|cascade];
默认为restrict ,删除时该表不能被其他表的约束所引用,无视图,无触发器等。否者无法删除。
cascade时,表和表上建立的一起都被删除。