約束
五種約束:
not null 非空
unique 唯一 允許出現多個null
primary key 主鍵 唯一,非空,一個表只允許創建一個主鍵
foreign key 外鍵 必須爲引用表中主鍵列的值或者爲null
check 檢查
在定義primary key或unique約束後系統會自動在對應的列上創建唯一性索引
可以在列級或表級定義約束
- 列級: 列名 列類型 約束
- 表級: constraint 約束名 約束類型 (指定列)
1.列名 類型 約束 -->系統自動創建索引並命名SYS_....
create table my_table(
t_id number unique
)
2.列名 類型..... constraint 約束名 約束類型 (指定列)
create table my_table1(
t_id number(10) ,
constraint t_id_uk unique (t_id)
)
非空 (not null)約束 只能定義在列上
列級約束只能作用在一個列上,表級約束能作用在多個列
主外鍵
主鍵:constraint 主鍵名 primary key (主鍵列)
外鍵:constraint 外鍵名 foreign key (外鍵列) references 引用父表(父表的主鍵列)
先創建父表(主鍵表)
create table supertable(
sup_id number,
constraint supertable_sup_id_pk primary key (sup_id)
)
創建子表(外鍵表,應用父表的主鍵)
create table sontable(
son_id number unique,
son_name varchar2(20),
fatherid number,
constraint sontable_fatherid_fk foreign key (fatherid) references supertable(sup_id)
)
在sontable中的fatherid列插入數據時,只能是supertable(父表)sup_id列的數據,或者爲null
在刪除supertable(父表)中的數據時,不能是sontable(子表)中fatherid(外鍵列)引用的,除非先把子表的外鍵列的值刪除修改或置爲null,沒被外鍵列引用的可以直接刪除
on delete cascade (級聯刪除)
當父表中的主鍵列被刪除時,子表中相對應的列也被刪除
constraint sontable_fatherid_fk foreign key (fatherid) references supertable(sup_id) on delete cascade
- on delete set null (級聯置空)
當父表中的主鍵列被刪除時,子表中相對應的列置爲空
當自表外鍵列設置了級聯時,就可以在父表中隨意刪除了
檢查約束
create table emp(
e_id number unique,
e_name varchar2(20) not null,
salary number(10) check (salary between 0 and 100000)
)
create table emp(
e_id number unique,
e_name varchar2(20) not null,
salary number(10) ,
constraint salary_ck check (salary between 0 and 100000 and length(e_name)>5)
)
添加/刪除約束 但不能修改約束
添加約束
alter table 表名 add constraint 約束名 約束類型 指定列
添加 not null 約束時需要用關鍵字 modify
alter table 表名 modify 指定列 not null
create table emp(
e_id number ,
e_name varchar2(20) ,
salary number(10)
)
--添加約束
alter table emp add constraint e_name_uk unique (e_name)
alter table emp modify e_name not null
insert into emp (e_name)values ('s')
select * from emp
--刪除約束
alter table emp drop constraint e_name_uk
--禁用約束
alter table emp disable constraint e_name_uk
--激活約束
alter table emp enable constraint e_name_uk
查詢數據字典
user_constraint 所有約束
user_cons_columns 定義約束的列
在有where指定 table_name 時需要大寫表名
select * from user_constraints where table_name ='EMP'
select * from user_cons_columns