2

我有以下表格:

CREATE TABLE BOOK_AUTHORS
(Book_id CHAR(20) NOT NULL,
AuthorName VARCHAR(30) NOT NULL,
PRIMARY KEY (Book_id, AuthorName),
FOREIGN KEY (Book_id) REFERENCES BOOK (Book_id));

CREATE TABLE BOOK_COPIES
(Book_id CHAR(20) NOT NULL,
Branch_id CHAR(20) NOT NULL,
No_of_copies NUMBER,
PRIMARY KEY (Book_id, Branch_id),
FOREIGN KEY (Book_id) REFERENCES BOOK (Book_id),
FOREIGN KEY (Branch_id) REFERENCES LIBRARY_BRANCH (Branch_id));

我想为ON DELETE CASCADE它们添加约束:

我第一次尝试它说它有效。该文件如下所示:

ALTER TABLE "BOOK_AUTHORS"
ADD CONSTRAINT "fk_test"
FOREIGN KEY ("Book_id")
REFERENCES "BOOK" ("Book_id")
ON DELETE CASCADE;

然后我为第二个表中的两个外键制作了两个单独的表:

ALTER TABLE "BOOK_COPIES"
ADD CONSTRAINT "fk_test1"
FOREIGN KEY ("Book_id")
REFERENCES "BOOK" ("Book_id")
ON DELETE CASCADE;

ALTER TABLE "BOOK_COPIES"
ADD CONSTRAINT "fk_test2"
FOREIGN KEY ("Branch_id")
REFERENCES "LIBRARY_BRANCH" ("Branch_id")
ON DELETE CASCADE;

但是,这样做后我得到了错误

“Book_id”无效标识符

接着

“Branch_id”无效标识符

我不知道我做错了什么。然后我返回并再次执行了第一个 alter table(我最初认为有效的那个),它给了我相同的错误消息 ( "Book_id" invalid identifier)。有人可以帮我添加这些约束吗?我还有五个其他表可以添加这些约束。

4

3 回答 3

3

如果您在标识符周围加上双引号(就像您在

ALTER TABLE "BOOK_COPIES"
ADD CONSTRAINT "fk_test1"
FOREIGN KEY ("Book_id")
REFERENCES "BOOK" ("Book_id")
ON DELETE CASCADE;

)您的标识符(例如,在这种情况下为“Book_id”)变得区分大小写。

因此,您要么必须更改表定义并将列重命名为“Book_id”,要么(最好是恕我直言)只需去掉约束定义中的双引号:

ALTER TABLE BOOK_COPIES
ADD CONSTRAINT fk_test1
FOREIGN KEY (Book_id)
REFERENCES BOOK (Book_id)
ON DELETE CASCADE;
于 2013-10-22T07:59:20.810 回答
2

首先让我澄清一件事,您不能将删除级联添加到已经存在的外键约束,如文档中所示,您只能更改其状态,这意味着启用或禁用,以防万一您需要添加然后删除约束第一的。这个问题被问了两次,还在重复,请版主看看这个。以下是已经解决您问题的链接。第一第二第三,谁知道有多少关于删除级联的问题。

于 2015-09-28T14:16:07.640 回答
0

将双引号 (") 放在表名和列名周围。

我添加了表“BOOK”和表“LIBRARY_BRANCH”:

CREATE TABLE "BOOK"
("Book_id" CHAR(20) NOT NULL,
"BookName" VARCHAR(30) NOT NULL,
PRIMARY KEY ("Book_id"));

CREATE TABLE "BOOK_AUTHORS"
("Book_id" CHAR(20) NOT NULL,
"AuthorName" VARCHAR(30) NOT NULL,
PRIMARY KEY ("Book_id", "AuthorName"));

CREATE TABLE "LIBRARY_BRANCH" 
("Branch_id" CHAR(20) NOT NULL, 
 "Branch_name" VARCHAR(50), 
 "Address" VARCHAR(100), 
 PRIMARY KEY ("Branch_id"));

CREATE TABLE "BOOK_COPIES"
("Book_id" CHAR(20) NOT NULL,
"Branch_id" CHAR(20) NOT NULL,
"No_of_copies" NUMBER,
PRIMARY KEY ("Book_id", "Branch_id"));


ALTER TABLE "BOOK_AUTHORS"
ADD CONSTRAINT "fk_test"
FOREIGN KEY ("Book_id")
REFERENCES "BOOK" ("Book_id")
ON DELETE CASCADE;

ALTER TABLE "BOOK_COPIES"
ADD CONSTRAINT "fk_test1"
FOREIGN KEY ("Book_id")
REFERENCES "BOOK" ("Book_id")
ON DELETE CASCADE;

ALTER TABLE "BOOK_COPIES"
ADD CONSTRAINT "fk_test2"
FOREIGN KEY ("Branch_id")
REFERENCES "LIBRARY_BRANCH" ("Branch_id")
ON DELETE CASCADE;

sqlfiddle demo

于 2013-10-22T01:04:51.963 回答