我在向现有表添加具有两个约束条件的约束时遇到困难。我正在处理下面的两个关系,并且我试图将约束添加到" books"表。
关系是:
图书((book_id),标题, author_id , subject_id )
科目((subject_id),科目,地点)
parantheses中的键是主键,斜体是外键。
第一个条件/条件是 subject_id 不是NULL,并且在将新的图书元组插入图书时 subject_id 已经必须作为主体关系中的主键。
ALTER TABLE books ADD CONSTRAINT hasSubject
CHECK(subject_id IS NOT NULL AND subject_id REFERENCES subjects(subject_id))
我一直收到错误消息:"语法错误在或附近' REFERENCES'"
有什么想法吗?先感谢您!
答案 0 :(得分:1)
REFERENCES
是一种单独的约束类型。所以,你需要两个约束:
ALTER TABLE books ADD CONSTRAINT chk_books_subject_id
CHECK (subject_id IS NOT NULL);
ALTER TABLE books ADD CONSTRAINT fk_books_subject_id
FOREIGN KEY (subject_id) REFERENCES subjects(subject_id);
我把它们放在两个ALTER TABLE
语句中,以强调它们是不同的。它们可以合并为一个声明。
编辑:
在一个声明中:
ALTER TABLE books
ADD CONSTRAINT chk_books_subject_id CHECK (subject_id IS NOT NULL),
ADD CONSTRAINT fk_books_subject_id FOREIGN KEY (subject_id) REFERENCES subjects(subject_id);