php - MySQL:获取列出所有属性的产品

标签 php mysql

我在使此查询按预期工作时遇到了一些问题。

我有三个表:productsproduct_attributesattributes
关系很明显(一个产品可以有多个属性)

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/

相关文章:

php - 在 div 中加载新页面

php - 修复 WordPress 自定义菜单字符编码

javascript - 无法弄清楚这个 if 语句有什么问题?

php - 在 php 中引用数组中的姐妹元素

mysql - 使用 CASE 更新列中的值

MySQL选择所有最后添加的查询

MYSQL 命令行 SELECT INTO OUTFILE, LOAD DATA INFILE ... INTO TABLE 到 CSV,列中包含 html 数据

MYSQL - 查找行,其中部分搜索字符串与列中的部分值匹配

php - Yii 框架的 I18n 基础

php - mysql 准备好的语句,既没有错误也没有数据库中的数据