如果输入列表中存在所有相关值,如何仅包含结果

How to only include result if all related values exist in input list

我有一个包含许多 Tag 的对象 Product。我想编写一个查询,给定一个 Tag id 列表,如果所有产品的标签都包含在输入列表中,则只有 returns a Product。输入列表可能包含不属于产品的标签 ID,但没关系,产品仍然可以退回(即所有产品的标签必须作为输入列表的子集存在才能包含在结果中)。

我能够编写 1 个查询来完成此操作,但我真的希望能够在没有 JOIN 中的子查询的情况下完成此操作。这就是我所拥有的:

SELECT *
FROM product
LEFT JOIN product_tag ON product_tag.product_id = product.id
LEFT JOIN (
    SELECT product.id, COUNT(*) AS record_count
    FROM product
    LEFT JOIN product_tag ON product_tag.product_id = product.id
    GROUP BY product.id
) AS inner_q ON inner_q.id = product.id
WHERE product_tag.id in (1, 2, 3) -- Sample Tag ids
GROUP BY product.id
HAVING COUNT(*) = inner_q.record_count

这是否为您提供了所需的结果?

select * from product 
where id in 
(select product_id
 from product_tag 
 group by product_id
 having sum(case when id in (1, 2, 3) then 1 else 0 end) >= 3)

vkp 引导我走向正确的方向:

select * from product 
where id in 
(
 select product_id
 from product_tag 
 group by product_id
 having sum(case when id in (1, 2, 3) then 1 else 0 end) >= count(product_id)
)