Mysql SELECT其中2列匹配值集

时间:2013-05-11 04:32:48

标签: mysql sql

我正在做产品过滤这一点是用户选择产品越具体,应该出现的结果越少。在他的那一刻,我正在编写多个查询并存储在数组中并检查数组相交,但结果相反,这意味着当用户应用更多过滤器时,我将显示更多产品。

所以我认为可能有一个我不知道的SQL命令!

简化示例:

------------
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  ...

如何选择(page = 200和langauge = en)?

2 个答案:

答案 0 :(得分:3)

如果理解正确,你可能正在寻找类似的东西

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

输出:

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

<强> SQLFiddle

答案 1 :(得分:1)

另一种选择,但不那么优雅。我只想展示另一种方式。

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);