4

再会!

我一直在 Internet 上搜索我的问题的答案,但一直没有找到答案。如何从 Derby 数据库的不同表中引用外键?

这是我当前的 SQL 代码:

CREATE TABLE class_t
(course_id VARCHAR(6) NOT NULL,
semester VARCHAR(6) NOT NULL CONSTRAINT sem_constraint CHECK (semester IN ('1st','2nd','module')),
school_year DATE NOT NULL,
course_name VARCHAR(70) NOT NULL,
CONSTRAINT class_pk PRIMARY KEY (course_id, semester, school_year)
);

CREATE TABLE student_t
(id_number INT NOT NULL,
fullname VARCHAR(35) NOT NULL,
contact_num VARCHAR(35),
email VARCHAR(25),
CONSTRAINT student_pk PRIMARY KEY (id_number)
);

CREATE TABLE student_list
(course_id VARCHAR(6) NOT NULL,
semester VARCHAR(6) NOT NULL CONSTRAINT sem_constraint2 CHECK (semester IN ('1st','2nd','module')),
school_year DATE NOT NULL,
id_number INT NOT NULL,
CONSTRAINT student_list_pk PRIMARY KEY (course_id, semester, school_year, id_number),
CONSTRAINT student_list_FK FOREIGN KEY (course_id, semester, school_year, id_number)
REFERENCES class_t (course_id, semester, school_year), student_t (id_number) #this is my problem
);

非常感激您的帮忙!提前致谢。

4

1 回答 1

4

没关系,我自己想通了。当我查看示例部分中的http://db.apache.org/derby/docs/10.2/ref/rrefsqlj13590.html时,对解决方案有所了解。来自不同表的每个外键应该有不同的约束。它应该是这样的:

CREATE TABLE student_list
(course_id VARCHAR(6) NOT NULL,
semester VARCHAR(6) NOT NULL CONSTRAINT sem_constraint2 CHECK (semester IN ('1st','2nd','module')),
school_year DATE NOT NULL,
id_number INT NOT NULL,
CONSTRAINT student_list_pk PRIMARY KEY (course_id, semester, school_year, id_number),
CONSTRAINT student_list_fk1 FOREIGN KEY (course_id, semester, school_year)
REFERENCES class_t (course_id, semester, school_year),
CONSTRAINT student_list_fk2 FOREIGN KEY (id_number)
REFERENCES student_t (id_number)
);

感谢您对 stackoverflow.com 社区的所有帮助!:)

于 2012-04-13T01:11:57.277 回答