CHIL-ORACLE-主外键约束(primary key / foreign key)

主键约束
  要求主键列数据唯一,并且不允许为空

外键约束
  用于量表建立关系,需要指定引用朱彪的那列(主表必须是主键)
1
.主键约束 ( primary key ) --例如1: create table test( c number(10) primary key ); --例如2: create table test1( c number(10) constraint pk_c primary key ); --例如3: create table test2( c number(10) , primary key(c) ); --例如4: create table test3( c number(10), c1 number(10), primary key (c,c1) ); --例如5: create table test4( c number(10) , constraint pk_test4_c primary key (c) ); 2.给建好的表创建主键: --例如6: create table test5( c number(10) ); alter table test5 add primary key (c); 3.给建好的表添加主键:不使用默认主键名,自定义主键名 --例如7: create table test6( c number(10) ); alter table test6 add constraint pk_test6_c primary key(c); 4.外键约束 ( foreign key ) --例如1:Fk 使用“列级约束”来进行建表: create table test8( a1 number(10) primary key ); create table test9( b1 number(10) primary key, b2 number(10) references test8(a1) ); --例如2:Fk 使用“表级约束”来进行建表: Create table test10 ( a1 number(10) primary key ); Create table test11( b number(10) primary key, b2 number(10), foreign key(b2)references test10(a1) ); --例如3: Create table test12 ( a1 number(10) primary key ); Create table test13( b number(10) primary key, b2 number(10), foreign key(b2)references test12(a1) ); --例如4: Create table test14 ( a1 number(10) ); alter table test14 add constraint pk_test14_c primary key(a1); Create table test16( b number(10), b2 number(10) ); alter table test16 add constraint pk_test16_c foreign key(b) references test14(a1); 5.级联删除: --例如一:(如果删除父表中的某条记录,子表相应记录也被删除) create table test17( id number primary key ); 插入操作:insert into test17(id)values(1); create table test18( id number primary key, p_id number references test17(id) on delete cascade ); 插入操作:insert into test18 values(1,1); 删除操作:delete from test17 where id=1;--注意:发现子表的数据已经没有了 --例如二:(如果删除父表某条记录,子表相应记录被置空) create table parent( id number primary key ); insert into parent values (1); create table chile( id number primary key, p_id number references parent(id) on delete set null ); 插入操作:insert into chile values(1,1); 删除操作:delete from parent where id=1; --注意:删除父表时子表对应列为空 6. Foreign Key 的可选参数 ON DELETE CASCADE 在创建 Foreign Key 时可以加可选参数: ON DELETE CASCADE 它的含义是如果删除外键主表里的内容,子表里相关的内容将一起被删除. 如果没有 ON DELETE CASCADE 参数,子表里有内容,父表里的主关键字记录不能被删除掉.

 

posted @ 2017-03-07 10:11  CHIL  阅读(347)  评论(0编辑  收藏  举报