您通过通用产品 ID 加入是一回事,这只是直接条件。要包含多个类别,您只需使用“IN”子句并提供您感兴趣的不同类别的列表。
SELECT
*
FROM
oc_product p
INNER JOIN oc_product_to_category pc
ON p.product_id = pc.product_id
AND pc.category_id IN ( 101, 102, 301 )
现在,您的问题不清楚,但是如果您试图暗示您正在寻找属于 A 类但也与 B 类相关联的产品,并且希望确保这两个类别都被涵盖。以计算机为例。你卖电脑。有人对笔记本电脑(A 类)感兴趣,但也对 i7 处理器(B 类)和 15 英寸屏幕(C 类)感兴趣。您要确保所有 3 个感兴趣的类别都在结果中。您不需要 13 英寸笔记本电脑,也不需要 i7 台式机/塔式机。如果这种情况更多,您可能希望对所需的 3 个类别进行汇总计数。在这种情况下,我会从满足所有 3 个要求的产品/类别表中进行预查询聚合,然后获得符合条件的产品。类似的东西
select
p.*
from
( select
-- I only care about the final product ID that qualifies
pc.product_id
from
oc_product_to_category pc
where
-- the product category must be of these 3 possible choices
pc.category_id in ( 101, 102, 301 )
group by
pc.product_id
having
-- first SUM() qualifies that the 301 MUST BE included
-- hence its = 1 value.
sum( case when pc.category_id = 301
then 1 else 0 end ) = 1
AND
-- AND the sum() of the others is GREATER than 0.
-- so either OR both would qualify the product
sum( case when pc.category_id in ( 101, 102 )
then 1 else 0 end ) > 0 ) JustQualified
-- NOW, joining to the products based on only those that qualified above
JOIN oc_product p
on JustQualified.product_id = p.product_id
相关更新
要对上述查询中我作为别名“p”的 OC_Product 表执行相关更新查询,只需对语法稍作更改
update oc_product p
JOIN ( select
-- I only care about the final product ID that qualifies
pc.product_id
from
oc_product_to_category pc
where
-- the product category must be of these 3 possible choices
pc.category_id in ( 101, 102, 301 )
group by
pc.product_id
having
-- first SUM() qualifies that the 301 MUST BE included
-- hence its = 1 value.
sum( case when pc.category_id = 301
then 1 else 0 end ) = 1
AND
-- AND the sum() of the others is GREATER than 0.
-- so either OR both would qualify the product
sum( case when pc.category_id in ( 101, 102 )
then 1 else 0 end ) > 0 ) JustQualified
-- NOW, joining to the products based on only those that qualified above
on JustQualified.product_id = p.product_id
set p.myColumn = 22