我使用以下查询来查找具有所提供标签的所有项目,并且效果很好:
select items.*
from items
inner join item_tag on items.id = item_tag.item_id
where items.deleted_at is null and published = 1
and brand_id = 1
and item_tag.tag_id in (1,2,3)
group by items.id
having COUNT(DISTINCT item_tag.tag_id) = 3 order by id desc
我正在尝试进行一个查询,该查询返回未由所提供的标签标记的所有项目,但它无法按预期工作。
select items.*
from items
inner join item_tag on items.id = item_tag.item_id
where items.deleted_at is null and published = 1
and brand_id = 1
and item_tag.tag_id not in (4,5,6)
group by items.id
having COUNT(DISTINCT item_tag.tag_id) = 0 order by id desc
查询还应该使用“in”和“not in”标签的组合。有人有建议吗?
最佳答案
having
子句的技巧无法排除带有某些标签的项目,因此您需要以不同的方式进行处理。事实上,如果没有 having
子句,第二个查询会返回更好的结果。
您仍然无法将 in
和 not in
的条件结合起来。对于这种情况,我建议像这样的查询:
select items.*
from items
inner join (
select item_id, count(distinct tag_id) as matches
from item_tag
where tag_id in (1,2,3)
group by item_id
) as tags_in
on tags_in.item_id = items.id
left join (
select item_id
from item_tag
where tag_id in (4,5,6)
group by item_id
) as tags_out
on tags_out.item_id = items.id
where items.deleted_at is null
and items.published = 1
and items.brand_id = 1
and tags_in.matches = 3
and tags_out.id is null
因此,第一个连接获取具有应存在的标签计数的项目,第二个连接获取具有禁止标签的项目。然后 where
子句对两者执行最终测试。
关于mysql - 查找未标记以下标签的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35899668/