tags:

views:

223

answers:

2

I have these three table to store tags for photo albums. Here is the schema

table 1: Albums
Album_ID
Album_Name

table 2: AlbumTags
Tag_ID
Tag_Name

table 3: AlbumTagBridge
ID
Tag_ID
Album_ID

What is the most efficient SQL to be able to come up with a result set that looks like this:

Tag_Name | Count
Tag 1 | 19
Tag 2 | 3
Tag 3 | 17

A: 
Select Tag_Name, COUNT(AlbumTagBridge.ID)
From AlbumTags
Join AlbumTagBridge USING(Tag_ID)
Group By Tag_Name

Grouping by AlbumTags.Tag_ID, Tag_name might possibly be a tad cheaper depending on your indexing &c (especially if your SQL engine isn't all that smart;-), but since you tell us nothing about your indices nor about your engine this is about the best we can do.

Alex Martelli
right now i have no indexing at all. i am using SQL server 2008
ooo
This code also assumes that tag names are unique; i.e., that there are no two tags whose IDs are different but names are the same. I think this is a good assumption that should be enforced with a unique constraint.
Bugmaster
that is a fine assumtion
ooo
running this query gives me an error:"Tag_ID" is not a recognized table hints option. If it is intended as a parameter to a table-valued function or to the CHANGETABLE function, ensure that your database compatibility mode is set to 90.
ooo
try `Join AlbumTagBridge ON AlbumTagBridge.Tag_ID = AlbumTags.Tag_ID` then -- not sure why it would object to `USING` but it seems it is!-)
Alex Martelli
+1  A: 
SELECT dbo.AlbumTags.Tag_Name, 
       COUNT(dbo.AlbumTagBridge.Tag_Id) AS Cnt
FROM dbo.AlbumTagBridge 
INNER JOIN dbo.AlbumTags ON dbo.AlbumTagBridge.Tag_Id = dbo.AlbumTags.Tag_ID
GROUP BY dbo.AlbumTags.Tag_Name
rick schott
I am assuming you don't care about the Albums but just tag counts across them all.
rick schott