mysql cross check tag query
I have two tables one with Items and one with tags I want to find every item in the items table that has the tag "foo" but not the tag bar so if I where going to select all items that have the tag "foo" my query would be
SELECT * FROM items i INNER JOIN tags t on i.id= t.id WHERE tag= "foo"
and I开发者_开发百科 get all items with tags of "foo" so how do I subquery to take out all the items that are also tagged "bar"
EDIT based on Matthew Coxa solution provided bellow I cam up with this if anyone sees any flaw with this please let me know
SELECT * FROM items i INNER JOIN
tags t ON t.item_id=i.id
WHERE tag = 'foo'
AND NOT EXISTS (
SELECT * FROM tags tt WHERE t.item_id = tt.item_id AND tag = 'bar'
)
SELECT *
FROM items i
INNER JOIN tags t
ON i.id = t.id
WHERE t.tag = "foo" AND NOT EXISTS (
SELECT *
FROM items ii
INNER JOIN tags tt
ON ii.id = tt.id
WHERE tt.tag = "bar" AND tt.id = t.id)
select
*
from
items i
where
exists (select * from tags t where t.id = i.id and t.tag = "foo")
and
not exists (select * from tags t where t.id = i.id and t.tag = "bar")
or
;with ItemTagCount as (
select
t.id,
sum(case t.tag when "foo" then 1 else 0 end) as FooCount,
sum(case t.tag when "bar" then 1 else 0 end) as BarCount
from
tags t
group by
t.id
)
select
i.*
from
items i
inner join
ItemTagCount itc on itc.id = i.id
where
itc.FooCount >= 1 and itc.BarCount = 0
精彩评论