Oracle Foreign key

来源:互联网 发布:python 字典值为数组 编辑:程序博客网 时间:2024/05/09 14:30

http://mgracy.blog.163.com/blog/static/57649898200971995640136/

 

 

A foreign key is a column in a table that does not uniquely identify rows in that table, but is used as a link to matching columns in other tables to indicate a relationship.

For example, the Hr_Emp.deptNo column is a foreign key pointing the the Hr_Dept table's primary key - Hr_Dept.deptNo.

Examples

Inline and out of line definitions

1. Define a table with primary key to reference:

CREATE TABLE t1 (c1 NUMBER PRIMARY KEY);

2. Inline foreign key (part of column definition):

CREATE TABLE t2 (
        c1 NUMBER PRIMARY KEY,
        c2 NUMBER REFERENCES t1(c1) );

3. Out-of-line foreign key (after column definitions):

CREATE TABLE t3 (
        c1 NUMBER,
        c2 NUMBER,
        CONSTRAINT t1_fk FOREIGN KEY (c1) REFERENCES t1);

ON DELETE CASCADE

Foreign key with ON DELETE CASCADE:

CREATE TABLE parent (id NUMBER PRIMARY KEY);
CREATE TABLE child  (id NUMBER PRIMARY KEY,
                    pid REFERENCES parent(id) ON DELETE CASCADE);

If rows are deleted from the parent table, referenced rows will automatically be removed from the child table.

ON DELETE SET NULL

Foreign key with ON DELETE SET NULL:

CREATE TABLE parent (id NUMBER PRIMARY KEY);
CREATE TABLE child  (id NUMBER PRIMARY KEY,
                    pid REFERENCES parent(id) ON DELETE SET NULL);

If rows are deleted from the parent table, referenced rows field will automatically be set to null in the child table.

原创粉丝点击