I'm building a 'tag' system for my blog posts. Currently my tags
table has columns tagid - MEDIUMINT NOT NULL AUTO_INCREMENT PRIMARY KEY
and tag VARCHAR(30) NOT NULL UNIQUE
.
And I have another table describing many to many relation between my blog posts and tags, table posttags
with columns postid,tagid
and dual PRIMARY KEY(postid,tagid)
.
Now when I started learning mysql, PRIMARY KEYs were all about the unique content. But now I understand that they are more of performance optimization things.
postid
is obviously an auto increment int.
Most of my queries are like :
- select all from posts join tags where postid = {postid},
- select all from posts join tags where tag = {tag name}.
Is my current DB structure good enough or are there any improvements I could make? also please suggest what all feilds should I make indexs, primary keys or unique?
UPDATE : InnoDB is the engine I'm using. Also, I have not defined any foreign keys as I don't see any benefit since my PHP side is capable of maintaining the integrity and consistency of data,
PRIMARY KEY
has only one job and that's what you said earlier - uniqueness. It just exists so you can distinguish between rows. Now, having an autoincremented integer is the easiest method to implement this kind of behaviour. Also, the smart guys that developed InnoDB used the integer-auto_incremented PK to also boost performance. To keep it short, there's nothing wrong with your DB schema, I doubt you can do much there except min/max maybe, but personally I wouldn't change anything.