简体   繁体   中英

Mysql SELECT where 2 column match set of values

I am doing product filter the point is the more specific the user select the products the less results should appear. At he moment I am writing multiple queries and storing in arrays and checking for array intersect, but the result is opposite, which means when user apply more filters, i will show more products.

So i am thinking there could be a SQL command which I don't know!

simplified example:

------------
table "filter"
------------
product
Spec
value


------------
Sample data
------------

book1,page,200
book1,cover,leather
book1,language,en

book2,page,300
book2,cover,paper
book2,language,de

book3,page,150
book3,cover,hard
book3,language,en



SELECT `product` FROM `filter` where  ...

how do I select (page=200 and langauge=en)?

If understand correctly you are probably looking for something like this

SELECT product
  FROM filter 
 WHERE (spec = 'page' AND value = '200')
    OR (spec = 'language' AND value = 'en')
 GROUP BY product
HAVING COUNT(*) = 2 -- 2 here represents number of spec-value pairs

Output:

| PRODUCT |
-----------
|   book1 |

SQLFiddle

Another alternative, but less elegant. I just wanted to show another way of doing it.

SELECT DISTINCT product
FROM filter f
WHERE 
    EXISTS (SELECT 1 FROM filter WHERE spec = 'language' AND value = 'en' AND product = f.product)
    AND EXISTS (SELECT 1 FROM filter WHERE spec = 'page' AND value = 200 AND product = f.product);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM