约束

来源:互联网 发布:top2000软件下载 编辑:程序博客网 时间:2024/05/21 17:26

约束

五种约束:

  • 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 nullinsert 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