Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Help with a 'tag' database select statement

Author  Topic 

lkelly
Starting Member

2 Posts

Posted - 2010-08-11 : 11:58:36
I have built a relatively simple group of tables to represent tags applied to a video. Sample tables are:


tbl_video
vid_id vid_name vid_description
1 test vid test description
2 red vid video is red
3 blue vid video is blue

tbl_tags
tag_id tag_name
1 new
2 old
3 interesting
4 boring

tbl_video_tags
vid_id tag_id
1 1
1 3
2 1
3 2
3 3
4 4


I'm looking for a query that will return all the fields in tbl_vid that match a LIST of tag_ids. (In this case tbl_tags isn't really needed for my example, but I'm including it for clarity.) For example, I would like to return the fields in tbl_video for all videos that are new (tag_id = 1) AND interesting (tag_id = 3). The result set would be the row for test_vid.

Can someone help? I have a query that returns all records with tag_ids of 1 OR 3, but not tag_ids 1 AND 3.

Thanks in advance - hopefully I have explained the situation clearly.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-08-11 : 12:12:39
[code]
SELECT v.*
FROM tbl_video v
INNER JOIN (SELECT vid_id
FROM tbl_video_tags
WHERE tag_id IN (1,3)
GROUP BY vid_id
HAVING COUNT(DISTINCT tag_id) = 2
)t
ON t.vid_id = v.vid_id
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -