mysql - 查找未标记以下标签的项目

标签 mysql sql

我使用以下查询来查找具有所提供标签的所有项目,并且效果很好:

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 子句,第二个查询会返回更好的结果。

您仍然无法将 innot 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/

相关文章:

php - SQL 查询执行时间急剧增加

mysql - 在同一服务器上迁移 Drupal 站点

c# - 使用 ASP.net 打开与 MySQL 的连接

php - Laravel Eloquent 仅选择不用作外键的数据

mysql - vb net 使用变量执行类似查询

java - 使用 JOOQ 记录存储过程的绑定(bind)值

php - 插入时将行数限制为特定数量

java - Swing表数据修改生成SQL

sql - 选择计数查询

sql - 获取每个订单的平均桌面数量 -SQL