2012-08-15 28 views
5

比方說,我有一個表使兩個表之間的結...是這樣的:IN()子句中的mysql相當於做邏輯與是不是

id_product | id_category 
----------------- 
11 | 22 
11 | 33 
12 | 22 
12 | 33 

我想id_products(不同)根據獲得搜索到的類別ID列表。

如果我使用IN()子句,則id_categories的列表使用邏輯或。

如何使SELECT查詢具有提交的id_categ列表的邏輯與?

例如:我想所有的id_products屬於類22 33(以及可能的更5+的ID CATEG)

我發現了這樣的回答: Using MySQL IN clause as all inclusive (AND instead of OR) ......但查詢混合更比1表...我只想要一個單一的表,結點之一的查詢。

+0

一個類別如何能同時等於22和33? – Kermit 2012-08-15 20:16:30

+0

我剛纔問完全相同的問題:http://stackoverflow.com/questions/11157772/sql-query-to-find-products-matching-a-set-of-categories – Tchoupi 2012-08-15 20:18:18

+0

@njk這是一個連接表。 .. – hsanders 2012-08-15 20:22:20

回答

6

讀你的鏈接,我認爲這會是這樣的

select id_product 
from yourTable 
where id_category in (--your List goes Here) 
group by id_product 
having count(distinct id_category) = NumberOfElementsOfYourList 

你應該使用=如果只是想拿到id_category,但沒有其他id_category。 如果沒有,使用> =

+1

我在'HAVING'子句中將COUNT(distinct id_product)'更改爲'COUNT(distinct id_category)'...對於每個id_product組,COUNT(distinct id_product)對於每個id_product組將始終爲1。 – Arth 2014-08-14 17:01:52

+0

你剛剛救了我的一天,今天。 :-) – Krenor 2016-02-29 09:48:48

1
select id_product 
from your_table 
where id_category in (22, 33) 
group by id_product 
having count(distinct id_category) = 2 

您可以添加having條款的罪名發現id_category的。例如,如果您查找5個ID,則必須更改having子句中的5中的2

+0

ElVieejo我認爲更快,但謝謝! – ecchymose 2012-08-15 20:52:39