我很震惊地将所有产品都存在于category_id 6,3中 为此我正在使用。
select c.product_id from product_to_category c where c.category_id = 6 and c.category_id = 3
为此返回0记录
如果我使用OR
代替AND
,
select c.product_id from product_to_category c where c.category_id = 6 or c.category_id = 3
然后,它返回与6或3 category_id
任何建议将不胜感激。
答案 0 :(得分:0)
您可以尝试使用IN
select c.product_id from product_to_category c where c.category_id IN (6,3)
当您使用AND时,它检查值c.category_id为6和3,看起来在您的情况下是不可能的。当你使用OR然后它就像你正在检查c.category_id是3还是6,即其中任何一个。
答案 1 :(得分:0)
您需要汇总:
select c.product_id
from product_to_category c
where c.category_id in (3, 6)
group by c.product_id
having count(*) = 2;
这是" set-within-sets"查询 - 您正在寻找具有特定产品ID集的产品。我喜欢使用group by
和having
来解决这个问题,因为这非常灵活地处理了许多不同的条件。
如果您可以有重复项,having
子句应为:
having count(distinct c.category_id) = 2