SQL ON DELTE CASCADE不起作用

时间:2017-05-21 19:26:23

标签: sql oracle foreign-keys ddl cascade

我目前正在使用Oracle SQL Developer编写数据库,我想使用ON DELETE CASCADE作为我的外键,但它显然不起作用。以下是有关的陈述。你可能会注意到没有更多的表,只有这两个用于测试。

CREATE TABLE pizza
(   size NUMBER(3),
    price NUMBER(5,2),
    CONSTRAINT pk_pizza PRIMARY KEY (size, price)
);
CREATE TABLE pizzacondiment 
(   condiment VARCHAR(30),
    pizzasize NUMBER(3),
    pizzaprice NUMBER(5,2),
    CONSTRAINT pk_condiments PRIMARY KEY (condiment, pizzasize, pizzaprice)
    CONSTRAINT fk_condiments_pizza FOREIGN KEY (pizzasize, pizzaprice)
    REFERENCES pizza (size, price)
    ON DELETE CASCADE;
);

现在,当我想丢弃表披萨时,输出显示:

ORA-02449: unique/primary keys in table referenced by foreign keys
02449. 00000 -  "unique/primary keys in table referenced by foreign keys"


*Cause:    An attempt was made to drop a table with unique or
           primary keys referenced by foreign keys in another table.


*Action:   Before performing the above operations the table, drop the
           foreign key constraints in other tables. You can see what
           constraints are referencing a table by issuing the following
           command:
           SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = "tabnam";

1 个答案:

答案 0 :(得分:4)

ON DELETE CASCADE适用于行级DML操作,但不会像DDL那样影响DROP。我将添加ON DELETE如何应用的示例,然后查看可以对drop语句进行的更改,以中断pizzapizzacondiment之间的链接,但留下孤立的{ {1}}处于可查询状态后面。

创建表格后:

pizzacondiment

并添加一些测试数据:

CREATE TABLE PIZZA
(
  "SIZE" NUMBER(3),
  PRICE  NUMBER(5, 2),
  CONSTRAINT PK_PIZZA PRIMARY KEY ("SIZE", PRICE)
);

CREATE TABLE PIZZACONDIMENT
(
  CONDIMENT  VARCHAR(30),
  PIZZASIZE  NUMBER(3),
  PIZZAPRICE NUMBER(5, 2),
  CONSTRAINT PK_CONDIMENTS PRIMARY KEY (CONDIMENT, PIZZASIZE, PIZZAPRICE),
  CONSTRAINT FK_CONDIMENTS_PIZZA FOREIGN KEY (PIZZASIZE, PIZZAPRICE)
  REFERENCES PIZZA ("SIZE", PRICE)
  ON DELETE CASCADE
);

当我们删除size = 11 pizza时,我们可以看到INSERT INTO PIZZA VALUES (11,1.25); INSERT INTO PIZZA VALUES (219,111.11); INSERT INTO PIZZA VALUES (50,7.50); INSERT INTO PIZZACONDIMENT VALUES ('Spinach',50,7.50); INSERT INTO PIZZACONDIMENT VALUES ('Peppers',50,7.50); INSERT INTO PIZZACONDIMENT VALUES ('Onions',50,7.50); INSERT INTO PIZZACONDIMENT VALUES ('Tomatoes',219,111.11); INSERT INTO PIZZACONDIMENT VALUES ('Mushrooms',11,1.25); INSERT INTO PIZZACONDIMENT VALUES ('Olives',11,1.25);

ON DELETE CASCADE

然后制作SELECT COUNT(*) AS CONDIMENT_COUNT FROM PIZZACONDIMENT WHERE PIZZASIZE = 11; CONDIMENT_COUNT 2

delete

再次检查子表:

DELETE FROM PIZZA WHERE "SIZE" = 11;
1 row deleted.

正如您所提到的,您希望SELECT COUNT(*) AS CONDIMENT_COUNT FROM PIZZACONDIMENT WHERE PIZZASIZE = 11; CONDIMENT_COUNT 0 DROP表{@ 1}}表,但留下孤儿PIZZA,您可以通过调整PIZZACONDIMENT来做到这一点语法,使用DROP。这将删除任何会阻止CASCADE CONSTRAINTS的外键,而不会留下孤立子表。

DROP

DROP TABLE PIZZA CASCADE CONSTRAINTS; Table PIZZA dropped. 是孤儿,但仍可使用:

pizzacondiment