I am reading a book called “MySQL developer’s library” by Paul DuBois and in the book he says:
CREATE TABLE score
(
student_id INT UNSIGNED NOT NULL,
event_id INT UNSIGNED NOT NULL,
score INT NOT NULL,
PRIMARY KEY (event_id, student_id),
INDEX (student_id),
FOREIGN KEY (event_id) REFERENCES grade_event (event_id),
FOREIGN KEY (student_id) REFERENCES student (student_id)
) ENGINE = InnoDB;
We made the combination of the two columns a PRIMARY KEY.
This ensures that we won’t have duplicate scores for a student
for a given quiz or test. Note that it’s the combination of
event_id
and student_id that is unique. In the score table, neither value
is unique
by itself. There will be multiple score rows for each event_id
value
(one per student), and multiple rows for each student_id value
(one for each
quiz and test) taken by the student
What is not clear to me is the combining two columns as one primary key… Meaning, I am having a hard time visualizing what is actually going on under the hood… It’s taking a collection of numbers [95, 210] for example and using that as a “key”… Is it appropriate to think of a primary key as a key to a hash?
Previously I always thought of primary keys as nothing more than unique ids for a table.. but now in this context, I am finding myself what a primary key actually is doing. Can anyone give me the low down on SQL keys?
A Primary Key is essentially it is a unique key with a not null constraint.
(as already mentioned, it is used to enforce referential integrity of your data)
It is simply a different type of primary key:
surrogate key / artificial key = usually a sequential number
http://en.wikipedia.org/wiki/Surrogate_key
natural key = column(s) that make the row unique
http://en.wikipedia.org/wiki/Natural_key
and here http://www.geeksengine.com/database/design/primary-key-constraint.php is a really good explanation of the differences.