0

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

所以我想可能有一个我不知道的 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  ...

如何选择(页面=200 和语言=en)?

4

2 回答 2

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

于 2013-05-11T04:37:46.443 回答
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);
于 2013-05-11T04:51:09.690 回答