SQL query to find resource containing more than one tag
I have two tables.
Resource:
md5 (PK), link, title
Tags:
md5 (FK), category
it is a one to many relationship such that a resource can have a number of tags. I want to be able to extract a resource that has both tags, for e.g. a resource that contains the tag 'web' and 'blog' in it. If I use 'OR', it will obviously r开发者_高级运维eturn even document that contain only 'web' or only contain 'blog', but if I use AND, I get no results even though I know there are resources that contain both tags
SELECT DISTINCT tags.MD5, Resource.Title, Resource.Link, tags.Category
FROM Resource
INNER JOIN tags ON Resource.MD5 = tags.MD5
WHERE
(tags.Category = @tag)
OR
(tags.Category = @tag2)
ORDER BY tags.MD5
You want to do like that:
select t.MD5, r.Title, r.Link, t.Category
from Resource r inner join Tags t on r.MD5 = t.MD5
where exists (select category from Tags t1 where category = @tag and t1.MD5 = r.MD5)
and exists (select category from Tags t1 where category = @tag2 and t1.MD5 = r.MD5)
The following will filter out resources that don't possess both tags:
SELECT DISTINCT Resource.MD5, Resource.Title, Resource.Link, t1.Category, t2.Category
FROM Resource
INNER JOIN tags t1 ON Resource.MD5 = t1.MD5 AND t1.category = @tag
INNER JOIN tags t2 ON Resource.MD5 = t2.MD5 AND t2.category = @tag2
select r.*
from resource as r
left join tags as t
on r.md5 = t.md5
where t.category in ('web','blog')
group by r.md5
having count(distinct(t.category)) = 2
精彩评论