Multi-Column Primary Key in MySQL 5
I'm trying to learn how to use keys and to break the habit of necessarily having SERIAL
type IDs for all rows in all my tables. At the same time, I'm also doing many-to-many relationships, and so requiring unique values on either column of the tables that coordinate the relationships would hamper that.
How can I define a primary key on a table such that any given value can be repeated in any column, so long as the combination of values across all columns is never repeated exactly?
Solution 1:
Quoted from the CREATE TABLE Syntax page:
A PRIMARY KEY can be a multiple-column index. However, you cannot create a multiple-column index using the PRIMARY KEY key attribute in a column specification. Doing so only marks that single column as primary. You must use a separate PRIMARY KEY(index_col_name, ...) clause.
Something like this can be used for multi-column primary keys:
CREATE TABLE
product (
category INT NOT NULL,
id INT NOT NULL,
price DECIMAL,
PRIMARY KEY(category, id)
);
From 13.1.20.6 FOREIGN KEY Constraints
Solution 2:
Primary key is a domain concept that uniquely (necessarily and sufficiently) identifies your entity among similar entities. A composite (multiple-column) primary key makes sense only when a part of the key refers to a particular instance of another domain entity.
Let's say you have a personal collection of books. As long as you are alone, you can count them and assign each a number. The number is the primary key of the domain of your library.
Now you want to merge your library with that of your neighbor but still be able to distinguish to whom a book belongs. The domain is now broader and the primary key is now (owner, book_id).
Thus, making each primary key composite should not be your strategy, but rather you should use it when required.
Now some facts about MySQL. If you define a composite primary key and want the RDBSM to autoincrement the ids for you, you should know about the difference between MyISAM and InnoDB behavior.
Let's say we want a table with two fields: parent_id, child_id. And we want the child_id to be autoincremented.
MyISAM will autoincrement uniquely within records with the same parent_id and InnoDB will autoincrement uniquely within the whole table.
In MyISAM you should define the primary key as (parent_id, child_id), and in InnoDB as (child_id, parent_id), because the autoincremented field should be the leftmost constituent in the primary key in InnoDB.