Ace Eusebio
Ace Eusebio

Reputation: 401

Derby: Referencing Multiple Foreign Keys From Different Tables

Good day!

I have been searching the Internet for an answer to my problem but I have not been able to get one. How do I reference foreign keys from different tables in a Derby database?

This is my current SQL code:

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
);

Your help is very much appreciated! Thanks in advance.

Upvotes: 4

Views: 6008

Answers (1)

Ace Eusebio
Ace Eusebio

Reputation: 401

Nevermind, I've figured it out myself. Had a clue at the solution when I looked at http://db.apache.org/derby/docs/10.2/ref/rrefsqlj13590.html in the examples part. There should be different constraints for each foreign keys from different tables. It should be like this:

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)
);

Thanks for all your help stackoverflow.com community! :)

Upvotes: 4

Related Questions