CREATE TABLE T_INVOICE
(ID NUMBER(10) NOT NULL,
INVOICE_NO VARCHAR2(30) NOT NULL,
CONSTRAINT PK_INVOICE_ID PRIMARY KEY(ID));
CREATE TABLE T_INVOICE_DETAIL
(ID NUMBER(10) NOT NULL,
AMOUNT NUMBER(10,3),
PIECE NUMBER(10),
INVOICE_ID NUMBER(10),
CONSTRAINT PK_DETAIL_ID PRIMARY KEY(ID));
ALTER TABLE T_INVOICE_DETAIL
ADD CONSTRAINT FK_INVOICE_ID
FOREIGN KEY(INVOICE_ID ) REFERENCES T_INVOICE(ID);
2、级联删除
外键语法有个选项可以指定级联删除特征。这个特征仅作用于父表的删除语句。使用这个选项,父表的一个删除操作将会自动删除所有相关的子表记录
ALTER TABLE T_INVOICE_DETAIL
ADD CONSTRAINT FK_INVOICE_ID
FOREIGN KEY(INVOICE_ID ) REFERENCES T_INVOICE(ID)
ON DELETE CASCADE;
如果不能级联删除,可设置子表外键字段值为null,使用on delete set null语句(外键字段不能设置not null约束).
ALTER TABLE T_INVOICE_DETAIL
ADD CONSTRAINT FK_INVOICE_ID
FOREIGN KEY(INVOICE_ID ) REFERENCES T_INVOICE(ID)
ON DELETE SET NULL;