tags:

views:

93

answers:

3

Hello,

After following this recommendation regarding tags tables structure, I've implemented the following design:

Table: Item
Columns: ItemID, Title, Content

Table: Tag
Columns: TagID, Title

Table: ItemTag
Columns: ItemID, TagID

I'm facing another problem, I wanna display the number each tag appears in the system. What's the best way to do this in terms of search query / php code that will not cause a severe performance impact (tags count will appear for each item).

Thanks,

Roy

+1  A: 
select count(*)
from ItemTag
where TagId = X

is mySQL that will get it dynamically.

If you're worried about the performance hit, you should store a count in the tag table, and increment/decrement it when you tag or untag an item.

Tom Ritter
Storing the tag count in tag table will do the trick. Thanks!
Roy Peleg
I wouldn't store the count. It's bound to get out of sync, and you'll have to do periodic queries to make sure it's correct. Use the SELECT COUNT(*) solution, because it will always be accurate. Enable the MySQL Query Cache as a transparent way to improve performance.
Bill Karwin
+2  A: 

Pretty sure the following (SQL) will get all the tag titles and associated counts of how often they appear on items.

select tag.title, count(itemtag.tagid) 
from tag, itemtag
where itemtag.tagid = tag.tagid
group by tag.title
Instantsoup
+1  A: 
SELECT Tag.Title, COUNT(Tag.TagID) AS TagCount
FROM ItemTag
LEFT JOIN Tag ON
(ItemTag.TagID = Tag.TagID)
GROUP BY Tag.Title
ORDER BY Tag.Title

Gives you a list of tags (ni alphabetical order) followed by the number of times they are used against an item. Unused tags do not appear.

_J_
There is no point to making this a LEFT JOIN.
Bill Karwin