2015-10-16 105 views
0

我很惊讶地得到所有存在于category_id中的产品6,3
这个我正在使用。mysql返回记录在哪里条款

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

所有特定产品

任何建议wo不胜感激。

+0

你要6类和3的所有记录?如果是,那么使用'OR'应该这样做。它有什么问题? – mynawaz

回答

0

你可以尝试当您正在使用,然后它被检查值c.category_id为6和3,它看起来像你的情况是不可能的

select c.product_id from product_to_category c where c.category_id IN (6,3) 

使用。当你使用OR时,它就像你正在检查c.category_id是3还是6,也就是两者之一。

+0

是的,它返回很多记录,就像一些产品存在于类别6有些在3,一些在两个(6,3),但我只需要那些记录存在于(6,3) –

+0

@HassanFarooq: - 你可以在这种情况下使用Gordon的查询。 –

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; 

这是一个“设置中集”查询的一个例子 - 你正在寻找谁拥有一组特定产品ID的产品。我喜欢使用group byhaving来解决这个问题,因为它非常灵活地处理许多不同的条件。

如果你能有重复,在having条款应该是:

having count(distinct c.category_id) = 2