views:

33

answers:

2

I' was wondering should my primary key look like this PRIMARY KEY (id, category_id, posts_id) or look like this PRIMARY KEY (id)?

Here is my MySQL table.

CREATE TABLE posts_categories (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
category_id INT UNSIGNED NOT NULL,
posts_id INT UNSIGNED NOT NULL,
date_created DATETIME NOT NULL,
PRIMARY KEY (id, category_id, posts_id),
UNIQUE KEY (category_id, posts_id)
);
+2  A: 

I recommend using:

PRIMARY KEY (category_id, posts_id)

The id value will always be unique - what won't be, is the paring of category_id and posts_id.

But I missed that you already have a unique key defined on the category_id and posts_id columns, so you're primary key could be just the id. But the primary key means that it will be a clustered index - you'll be searching for these two columns more than you would be the id column so searches should improve minutely over a non-clustered index on the two columns.

OMG Ponies
why is this the best bet?
maximus
the `UNIQUE KEY (category_id, posts_id)` is there to stop duplicate entries.
maximus
@maximus: In your question, that's redundant. See my update
OMG Ponies
@OMG Ponies so what are you trying to say?
maximus
@maximus: That's vague - what do you not understand?
OMG Ponies
So should my unique and primary keys look like this if I keep the id`PRIMARY KEY (id), UNIQUE KEY (category_id, posts_id)`
maximus
@maximus: No, my initial advice remains - frankly, I don't see any use in the `id` column.
OMG Ponies
but what if i keep the id?
maximus
@maximus: index the `id` if you like, but IMO it'd be a waste.
OMG Ponies
A: 

The multiple column key is called a Composite Key or a Compound Key

As stated they are completely valid and have benefits. See links. :-)

JustBoo