Oracle追加约束、删除约束的方法与外键约束的使用

添加添加约束有两种方法,一种是在创建表时添加约束,还有一种是创建表后添加约束

一、创建表时添加约束

  create table std (

  id number(3) primary key,

  name varchar2(10),

  address varchar2(20)

  );     或者

  creat table std (

  id number(3),

  name varchar2(10),

  address varchar2(20),

  contraint PK_id primary key

  );

二、创建表后添加约束

  对于唯一、主键、检查、外键约束

  语法:alter table 表名 add contraint 约束名称 约束类型 (列名);

  举例:alter table std add contraint NN_name not null(name);

 

  对于非空约束

  语法:alter table 表名 motify 列名 constraint 约束名称 not null;

 

  对于默认约束

  语法:alter table 表名 motify 列名 default '自定义的默认值'; 

 

删除约束:

一、对于唯一、主键、检查、外键、非空约束

  语法:alter table 表名 drop constraint 约束名;

 

二、对于默认约束

  语法:alter table 表名 motify 列名 default null; 

 

外键的使用:

一、通过外键,可以将两张表关联起来,A表中的a列--->B表中的b列,则a为外键,b为主键

二、语法:constraint FK_子表_外键列 foreign key(外键列) reference 父表(主键列);

 

create table sub(sid number, sname varchar(10) not null UNIQUE,
constraint PK_sid primary key(sid));  --创建课程表

insert into sub values(1,'Java');
insert into sub values(2,'Python');
insert into sub values(3,'C#');
commit;  --插入课程表数据

create table student( stuno number(3),stuname varchar2(10), stuaddress varchar2(20),stuid number(3), constraint FK_student_sub foreign key(stuid) references sub(sid));  --创建学生表,同时创建外键 insert into student values(1,'张三','广州市海珠区',1); insert into student values(2,'李四','广州市天河区',3); insert into student values(3,'王五','广州市越秀区',1);  --插入学生数据

 

三、注意

  1、主表中被引用的必须时主键或者唯一

  2、子表插入的数据在父表不存在时,会报错,例如:insert into student values(4,'赵六','广州市荔湾区',4)    --错误

  3、删除主表数据时,若关联的子表存在数据,则删除失败

 

四、外键使用建议:

  1、当父表中没有对应数据时,不要向子表增加数据

  2、不要更改父表的数据,导致子表孤立

  3、建议:在创建外键时,直接设置成 级联删除 或者 级联置空

  4、删除表的操作是:先删除子表,再删除父表

 

五、扩展

  若父表关联的子表存在数据,还是先直接删除父表数据时,可以使用级联删除,或者级联置空

  1、级联删除:删除父表数据时,会同时删除子表中关联的数据

     使用方式:在创建好的外键约束后面加上 on delete cascade

    create table student(
    stuno number(3),stuname varchar2(10),
    stuaddress varchar2(20),stuid number(3),
    constraint FK_student_sub foreign key(stuid) references sub(sid) on delete cascade
    ); 

 

  2、级联置空:删除父表数据时,会将子表中关联的外键值置空,其他字段不影响

     使用方式:在创建好的外键约束后面加上 on delete set null   

    create table student(
    stuno number(3),stuname varchar2(10),
    stuaddress varchar2(20),stuid number(3),
    constraint FK_student_sub foreign key(stuid) references sub(sid) on delete set null
    ); 

 

 

   

posted @ 2021-08-31 23:56  Brack_Pearl  阅读(1036)  评论(0编辑  收藏  举报