我在使此查询按预期工作时遇到了一些问题。
我有三个表:products
、product_attributes
和 attributes
。
关系很明显(一个产品可以有多个属性)
products
---------
id
product_attributes
------------------
product_id
attribute_id
attributes
----------
id
name
我想要实现的是获得那些具有给定属性列表的产品,但忽略那些只有部分所需属性列表的产品。
例如,具有这些产品和属性:
- 鞋子 1 [蓝色,男孩]
- 鞋子 2 [蓝色,女孩]
- 鞋子 3 [红色,男孩]
- 鞋子 4 [红色,女孩]
查询带有 [blue,boy] 的产品只会检索到 Shoe 1
。
查询带有 [blue] 的产品不会返回任何内容。
从现在开始我就在处理这个查询:
SELECT p.*, pa.attribute_id
FROM products AS p
LEFT JOIN product_attributes AS pa ON(pa.product_id=p.id)
WHERE
pa.attribute_id IN(' . implode(',', $attr_ids) . ')
GROUP BY p.id
HAVING count(pa.attribute_id)=' . count($attr_ids)
当只给出一个属性时,这会失败,因为它将返回任何具有该属性的产品。
最佳答案
-- PHP (or any other languaje) parts are hardcoded here!!!!
SELECT p.*, hma.howmuchattr
-- howmuchattr is needed by HAVING clause,
-- you can omit elsewhere (by surrounding SELECT or by programming languaje)
FROM products AS p
LEFT JOIN product_attributes AS pa ON pa.product_id = p.id
LEFT JOIN (
SELECT product_id, count(*) as howmuchattr
FROM product_attributes
GROUP BY product_id
) as hma on p.id = hma.product_id
WHERE
pa.attribute_id IN
(1,3) -- this cames from PHP (or any other languaje). Can be (1) for the other case
GROUP BY p.id
HAVING count(*) = howmuchattr;
参见 sqlfiddle这里
另见 this answer
关于php - MySQL:获取列出所有属性的产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17362148/