views:

76

answers:

2

I have a database that contains two tables:

  • entries
  • tags

The entries table contains posts that each have one or more tags. The problem is, each post can have any number of tags. In other words, I can't have a 'tag1', 'tag2', etc. column and do a LEFT JOIN.

How should I set up entries so that each post can have any number of tags?

+6  A: 

You need a mapping table.

Create a table called entries_tags that contains two columns: entry_id and tag_id, with a multi-key on both entries.

This is called a many-to-many relationship.

Borealid
Yea, and make sure no entry have duplicate tag. Updating tag will be a little tricky as you need to make sure existing ones remain, new ones added, deleted ones are removed. Of course yo can always remove all and then add them all over again to save you the trouble of comparing. Pros and cons I would say.
o.k.w
@o.k.w: You can handle all these issues via foreign key constraints and transactional updates.
Borealid
@o.k.w: Also, a primary key (preferrable) or a unique constraint on both columns would ensure uniqueness per combination.
OMG Ponies
Great! Could you please post a link to where I could read up a little bit on this?
George Edison
@George Edison: Sure, try http://philip.greenspun.com/sql/
Borealid
+1  A: 

You can also do it the SO-way, where in addition to having a junction/mapping/intersection table, you have a list of tags on the entry that's taggable:

entries table:
post_id: 3539744, .... tags: sql, database, database-design, tags, data-modeling

If you can't take the performance hit of using a junction table when pulling the associated tags for an entry. Of course extra care has to be taken here because you are dealing with denormalized data.

NullUserException