Select 枢轴中的 ID table 包括多个枢轴 ID,不包括一个枢轴 ID

Select IDs in pivot table including multiple pivot ID and excluding one pivot ID

如何select 属于两个类别的产品并删除一个类别?

示例:我希望select仅属于类别一和类别二的产品,不包括类别三。

产品必须同时具有类别一和类别二。

如果产品具有类别一、二和三则被排除。

我正在尝试做类似的事情,但它不起作用:

SELECT products.product_id , products.product_name FROM products
INNER JOIN product_category_relations ON product_category_relations.relations_product_id = products.product_id
WHERE relations_category_id IN (1,2) AND relations_category_id  NOT IN (3)
GROUP BY products.product_id

Product_id selected: 1 和 2.

示例产品 Table

product_id product_name
1 tshirt
2 pants
3 Bikini
4 Jumper

示例类别 Table

category_id category_name
1 category one
2 category two
3 category three
4 category four

枢轴 product_category_relations Table

relations_category_id relations_product_id
1 1
2 1
4 1
1 2
2 2
1 3
2 3
3 3
1 4
4 4

WHERE 子句中包括所有 3 个类别,并使用 HAVING 子句排除类别 3:

SELECT p.product_id , p.product_name 
FROM products p INNER JOIN product_category_relations pcr
ON pcr.relations_product_id = p.product_id
WHERE pcr.relations_category_id IN (1, 2, 3) 
GROUP BY p.product_id
HAVING COUNT(*) = 2 -- only 2 categories are allowed
   AND SUM(pcr.relations_category_id = 3) = 0 -- exclude category 3

或者,将 HAVING 子句简化为 GROUP_CONCAT():

HAVING GROUP_CONCAT(pcr.relations_category_id ORDER BY pcr.relations_category_id) = '1,2'