MySQL Selecting ID having both given values

limit :

Hopefully someone can help me out here.

I have a table structure like this

product_id  filter_id

374         54
374         55
37          64
375         52
375         55
375         56
375         64

I have a list of product_id's that I am using to do a WHERE IN

select product_id from product_filter WHERE product_id IN (375,37,251,252,261,262,263,264,269,270,271,272,277) and filter_id = 55 and filter_id = 56

I am trying to return all the prodcut ids that match the two filter AND statements. I run this and get nothing back, I also tried doing an INNER join back on the same table, but again nothing returned. Any idea how I can do this?

My expected result would be product 375 returned since it matches both "AND" filter_id statements.

Any help would be appreciated.

Arun Palanisamy :

I think you are looking for this.

SELECT PRODUCT_ID FROM PRODUCT_FILTER
WHERE PRODUCT_ID IN (375,37,251,252,261,262,263,264,269,270,271,272,277)
      AND FILTER_ID IN (55,56) 
GROUP  BY PRODUCT_ID
HAVING COUNT(DISTINCT FILTER_ID) = 2;

CHECK DEMO HERE

You can group by the product_id and check the count of filter_id. This will ensure that product ID matches both values.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=13856&siteId=1