文章目錄
- 一. 表
-
- <1> 建立表
-
- 1. 普通建表
- 2. 子查詢建表
- 3. 建立臨時表
- <2> 操作表
-
-
- 1. 修改表
- 2. 删除表
-
-
- (1) 删除表結構和内容
- (2) 僅删除表内容
-
-
- <3> 操作列
-
-
- 1 添加列
- 2 修改列
- 3 删除列
-
- <4> 操作注釋
- 二. 索引
-
- <1> 建立索引
-
- 1. 單列索引
- 2. 複合索引
- 3. 唯一索引
- <2> 維護索引
-
- 1.重建索引
- 2.删除索引
- 三. 限制
-
- <1> 建立限制
-
- 先區分-> 表級限制 和 列級限制
- 1. not null 非空限制
- 2. unique 唯一限制
- 3. primary key 主鍵限制
- 4. foreign key 外鍵限制
- 5. check 條件限制
- <2> 維護限制
-
- 1. 修改限制名
- 2. 激活/禁止限制
- 3. 删除限制
一. 表
<1> 建立表
1. 普通建表
create table department (
dep_no number(2) primary key comment '主鍵',
dep_name varchar2(20) not null ,
location varchar2(40) default 'QingDao' not null # 列名 類型 預設值 限制
);
2. 子查詢建表
create table emp_new (
name,
job,
salary,
hiredate )
as ( select
name,
job,
salsry,
hiredate
from
emp
where
dep_no = 30 );
3. 建立臨時表
create global temporary table employee_temp (
temp_no number(3)
);
<2> 操作表
1. 修改表
2. 删除表
(1) 删除表結構和内容
(2) 僅删除表内容
<3> 操作列
1 添加列
alter table department add(
sex char(4) default '無'
);
2 修改列
alter table department modify (
dep_no number(3) primary key
);
3 删除列
alter table department drop (
location
);
<4> 操作注釋
comment on table
employee is '雇員表';
comment on column
emmployee.emp_name is '雇員姓名';
// 想要删除注釋, 設定為空即可( 據說可以設定為 null??? 待嘗試, 待更新确認 ), 如下
comment on table employee is ' ';
二. 索引
<1> 建立索引
1. 單列索引
2. 複合索引
create index
index_dep_no_and_dep_name on department( dep_no, dep_name );
3. 唯一索引
// 注意建立唯一索引的列 不能有重複值 !
create unique
index_dep_no on department( dep_bo );
<2> 維護索引
1.重建索引
create index
index_dep_no
rebuild;
2.删除索引
三. 限制
<1> 建立限制
先區分-> 表級限制 和 列級限制
constraint
constraint_age check( age between 1 and 18 );
alter table
employee
add constraint
constraint_pone check( phone_no like '1%' );
1. not null 非空限制
2. unique 唯一限制
3. primary key 主鍵限制
4. foreign key 外鍵限制
# 列級
create table employee (
emp_no number(2) primary key,
emp_name varchar(12) not null,
age number(2) not null,
salary number(7) not null,
phone_no number(16),
dep_no number(2) constraint frk_dep_no references department(dep_no) );
# 表級
constraint
emp_primary
foreign key( dep_no ) references department( dep_no );
5. check 條件限制
check( sex in( '男', '女' ) )
check( sex = '男' or sex = '女' )
<2> 維護限制
1. 修改限制名
alter table
department
rename constraint
constraint_old
to
constraint_new;
2. 激活/禁止限制
alter table
department
disable
constraint_department;
alter table
department
enable constraint_department;
3. 删除限制
alter table
department
drop constraint
constraint_department;
# 注意删除主鍵的時候
alter table
department
drop primary key; # 删除此表的主鍵, 若有關聯會報錯
alter table
department
drop primary key cascade; # 級聯删除, 先解除此表的所有關聯, 再删除主鍵