关于 oracle 外键引用 与 goldengate
一、准备知识
约束放置在表中,有以下五种约束:
NOT NULL 非空约束C 指定的列不允许为空值
UNIQUE 唯一约束U 指定的列中没有重复值,或该表中每一个值或者每一组值都将是唯一的
PRIMARY KEY 主键约束P 唯一的标识出表的每一行,且不允许空值值,一个表只能有一个主键约束
FOREIGN KEY 外键约束R 一个表中的列引用了其它表中的列,使得存在依赖关系,可以指向引用自身的列
CHECK 条件约束C 指定该列是否满足某个条件
约束命名规则
如果不指定约束名Oracle server 自动按照SYS_Cn 的格式指定约束名,也可手动指定,
推荐的约束命名是:约束类型_表名_列名。
NN:NOT NULL 非空约束,比如nn_emp_sal
UK:UNIQUE KEY 唯一约束
PK:PRIMARY KEY 主键约束
FK:FOREIGN KEY 外键约束
CK:CHECK 条件约束
外键约束是用来维护从表和主表的引用完整性的,所以外键约束要涉及两个表。
FOREIGN KEY: 在表级指定子表中的列
REFERENCES: 标示在父表中的列
ON DELETE CASCADE: 当父表中的列被删除时,子表中相对应的列也被删除
ON DELETE SET NULL: 子表中相应的列置空
二、外键创建测试
foreign_main为主表
foreign_sub为从表
object_id做为foreign_sub的外键,参考主表foreign_main的object_id值
SQL> create table foreign_main as select object_id from all_objects;
Table created.
SQL> select count(*) from foreign_main;
COUNT(*)
----------
49571
SQL> create table foreign_sub as select object_id,object_name from all_objects;
Table created.
建议使用主表的主键做外键,即使不是主表的主键也应该是唯一约束的字段做为外键
SQL> alter table foreign_main add constraint pk_fsid primary key(object_id);
Table altered.
SQL> delete from foreign_sub where object_name = 'FOREIGN_MAIN';
1 row deleted.
SQL> commit;
Commit complete.
SQL> alter table foreign_sub add constraint fr_fssid foreign key(object_id) references foreign_main(object_id);
Table altered.
从表插入一条主表object_id中不存在的记录测试
SQL> insert into foreign_sub values(1,'ts');
insert into foreign_sub values(1,'ts')
*
ERROR at line 1:
ORA-02291: integrity constraint (TEST.FR_FSSID) violated - parent key not found
提示主表数据不存在,从表不能创建主表不存在的object_id以保证完整性
三、级联删除测试
SQL> alter table foreign_sub drop constraint fk_fs_oid;
Table altered.
SQL> alter table foreign_sub add constraint fk_fs_oid foreign key(object_id) references foreign_main(object_id) on delete cascade;
Table altered.
cascade下仍然不能单独更新主表外键字段
SQL> update foreign_main set object_id=52012 where object_id=52010;
update foreign_main set object_id=52012 where object_id=52010
*
ERROR at line 1:
ORA-02292: integrity constraint (TEST.FK_FS_OID) violated - child record found
cascade模式下可以通过主表删除外键字段数据关联删除从表数据
SQL> select * from foreign_sub where object_id=52010;
OBJECT_ID OBJECT_NAME
---------- ------------------------------
52010 IDX_BJNAME
SQL> delete from foreign_main where object_id=52010;
1 row deleted.
SQL> commit;
Commit complete.
SQL> select * from foreign_sub where object_id=52010;
no rows selected
外键相关常用操作及参考文档
建立外键
alter table 表名 add constraint 外键名 foreign key(从表外键字段) references foreign_main(主表外键字段);
drop表外键
alter table 表名 drop constraint 外键名;
通过外键找表
s