Theodore Sklavenitis
Theodore Sklavenitis

Reputation: 21

SQL compound Key

I am trying to create a table that as a Primary Key uses Values from other tables.My lectures said that this is a compound key (Primary+Foreign) yet I can't seem to be able to find how to initiate one.Can someone try to explain this concept and how to try to implement it?

Upvotes: 2

Views: 4062

Answers (1)

Himanshu
Himanshu

Reputation: 2454

Consider data which consists of sets of students and courses. When you store it in a DBMS each student (or course) will have an associated unique id, which will be called the primary key of the student (or course)

students(id, name, dob)
courses(id, name, credits)

To associate students with the courses they are enrolled in you will create a table which looks like this.

student_course(student_id, course_id)

To create this actually in mysql you would write something like:-

CREATE TABLE student_course(student_id INT NOT NULL, 
                            course_id INT NOT NULL, 
                            PRIMARY KEY (student_id, course_id),
                            FOREIGN KEY (student_id) REFERENCES student(id), 
                            FOREIGN_KEY (course_id) REFERENCES course(id))

Upvotes: 7

Related Questions