2015-10-16 127 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