美好的一天!
我一直在网上搜索我的问题的答案,但我一直无法得到。 如何引用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
);
非常感谢您的帮助!提前谢谢。
答案 0 :(得分: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社区! :)