我有以下表格:
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
)。有人可以帮我添加这些约束吗?我还有五个其他表来添加这些约束。
答案 0 :(得分: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;
答案 1 :(得分:1)
首先让我澄清一件事,你不能添加删除级联到已经存在的外键约束,如docs所示,你只能改变其状态,这意味着启用或禁用,如果你需要先添加然后删除约束。这个问题被问了两次,仍然重复请主持人一眼就看出来。以下链接已经解决了您的问题。 first,second和third以及谁知道有多少被问及有关删除级联的问题。
答案 2 :(得分: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;