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,
Best Answer
I think that the best for your
tag
andposttag
tables is:tagid
as a primary keytag
field (this cover your second query)INDEX(postid,tagid)
andINDEX(tagid,postid)
(this cover your first and second query)So:
And for your query: