我正在尝试添加删除级联,以便满足以下规则... •如果帐户持有人被删除,则必须删除属于该帐户持有人的所有帐户。
我收到错误,因为没有匹配的唯一密钥'和'无效的标识符'
CREATE table ACCOUNT_HOLDER
( Cust_ID Number (5) CONSTRAINT pk_custID PRIMARY KEY,
Birthday Date,
Gender Char (1) CONSTRAINT ck_gender CHECK (Gender IN ('M','F')),
Street varchar2 (20),
ZipCode Number (5),
City varchar2 (30),
Email varchar2 (30), CONSTRAINT fk_email FOREIGN KEY (email) REFERENCES Customer (email),
CONSTRAINT ck_email UNIQUE (Email));
CREATE table ACCOUNT
( Account# Number (5) CONSTRAINT pk_account PRIMARY KEY,
Payment_type varchar2 (15) CONSTRAINT ck_payment CHECK (Payment_type in ('Cash', 'Check', 'Credit', 'Debit')),
Date_created Date,
Cust_ID Number (5));
ALTER table ACCOUNT_HOLDER
ADD CONSTRAINT fk_account FOREIGN KEY (Account#) REFERENCES ACCOUNT (Account#) ON DELETE CASCADE;
答案 0 :(得分:0)
级联外键必须放在依赖数据上。在这种情况下,ACCOUNT
必须使用外键而不是ACCOUNT_HOLDER
通常,在依赖表中索引级联外键列也是一个好主意
下面是修订版本,在SQLPlus中有示例删除(我向客户注释了外键,因为该表不在示例中)
CREATE TABLE ACCOUNT_HOLDER
(
CUST_ID NUMBER(5) CONSTRAINT PK_CUSTID PRIMARY KEY,
BIRTHDAY DATE,
GENDER CHAR(1) CONSTRAINT CK_GENDER CHECK (GENDER IN ('M', 'F')),
STREET VARCHAR2(20),
ZIPCODE NUMBER(5),
CITY VARCHAR2(30),
EMAIL VARCHAR2(30),
-- CONSTRAINT fk_email FOREIGN KEY (email) REFERENCES Customer (email),
CONSTRAINT CK_EMAIL UNIQUE (EMAIL)
);
CREATE TABLE ACCOUNT
(
ACCOUNT# NUMBER(5) CONSTRAINT PK_ACCOUNT PRIMARY KEY,
PAYMENT_TYPE VARCHAR2(15) CONSTRAINT CK_PAYMENT CHECK (PAYMENT_TYPE IN ('Cash', 'Check', 'Credit', 'Debit')),
DATE_CREATED DATE,
CUST_ID NUMBER(5) REFERENCES ACCOUNT_HOLDER (CUST_ID) ON DELETE CASCADE
);
CREATE INDEX ACCOUNT_ACCOUNT_HOLDER_FKI
ON ACCOUNT (CUST_ID);
以下是SQLPlus中的示例级联:
SQL> INSERT INTO ACCOUNT_HOLDER (CUST_ID, BIRTHDAY, GENDER, STREET, ZIPCODE, CITY, EMAIL) VALUES
(1, SYSDATE, 'F', NULL, NULL, NULL, 'abc@123.net'); 2
1 row created.
SQL>
SQL> INSERT INTO ACCOUNT_HOLDER (CUST_ID, BIRTHDAY, GENDER, STREET, ZIPCODE, CITY, EMAIL) VALUES
(2, SYSDATE, 'M', NULL, NULL, NULL, '123@abc.net'); 2
1 row created.
SQL> INSERT INTO ACCOUNT (ACCOUNT#, PAYMENT_TYPE, DATE_CREATED, CUST_ID) VALUES
(1, 'Debit', SYSDATE, 1); 2
1 row created.
SQL>
SQL> INSERT INTO ACCOUNT (ACCOUNT#, PAYMENT_TYPE, DATE_CREATED, CUST_ID) VALUES
(2, 'Debit', SYSDATE, 1); 2
1 row created.
SQL> INSERT INTO ACCOUNT (ACCOUNT#, PAYMENT_TYPE, DATE_CREATED, CUST_ID) VALUES
(3, 'Debit', SYSDATE, 2); 2
1 row created.
SQL> COMMIT;
Commit complete.
SQL> SELECT COUNT(*) FROM ACCOUNT;
COUNT(*)
----------
3
SQL> DELETE FROM ACCOUNT_HOLDER WHERE CUST_ID = 1;
1 row deleted.
SQL> SELECT COUNT(*) FROM ACCOUNT;
COUNT(*)
----------
1