0

我有一个包含产品的类别和一组属性。这些属性是“形状”和“直径”。

当我打开一个类别而不应用过滤器时,我会得到带有以下查询的产品:

"SELECT * FROM `products` 
WHERE `category_id` 
IN ('6', '7', '29', '8', '9', '36')"

然后我点击属性“直径”(id = 2),值为“8mm”(id = 4)我生成以下查询:

"SELECT * FROM `products`
JOIN `products_attributes_values`
ON (`products_attributes_values`.`product_id` = `products`.`id`)
WHERE `category_id` IN ('6', '7', '29', '8', '9', '36')
AND `products_attributes_values`.`attribute_id` = 2
AND `products_attributes_values`.`value_id` = ('4')"

我得到了我需要的所有珠子“直径 8 毫米”然后我想更多地过滤我的产品并单击属性“形状”(id = 3),值为“圆形”(id = 11)我什么也没得到,查询看起来像:

"SELECT * FROM `products` 
JOIN `products_attributes_values`
ON (`products_attributes_values`.`product_id` = `products`.`id`)
WHERE `category_id` IN ('6', '7', '29', '8', '9', '36')
AND `products_attributes_values`.`attribute_id` = 2
AND `products_attributes_values`.`value_id` = ('4')
AND `products_attributes_values`.`attribute_id` = 3
AND `products_attributes_values`.`value_id` = ('11')"

所以我想要得到直径为 8 毫米和圆形的珠子,而不是什么都没有。单独所有过滤器都可以正常工作。当我想像上面的例子一样混合它们时,它只是不起作用。我需要如何修改查询以完成工作?

谢谢。

更新:

我想将一个属性上的多个值与另一个或多个属性结合起来。

例如,我想获得直径(id=2)为 8mm(id=4)或直径(id=2)10mm(id=5)和形状(id=3)为圆形(id=11)或形状的珠子(id=3) 刻面(id=62)

所以最后我想得到圆形或多面形状的 8 毫米或 10 毫米珠子。

4

1 回答 1

1

这 2 个过滤器需要单独处理,因为每个过滤器需要查看products_attributes_values表中完全不同的记录。

SELECT * FROM products
WHERE category_id IN ('6', '7', '29', '8', '9', '36')
    AND id IN (
        SELECT product_id
        FROM products_attributes_values
        WHERE attribute_id = 2
            AND value_id = '4')
    AND id IN (
        SELECT product_id
        FROM products_attributes_values
        WHERE attribute_id = 3
            AND value_id = '11')

来自 UAMoto:

它工作但有点慢,所以我使用了一个人告诉我的连接别名:

"SELECT * FROM `products`
JOIN `products_attributes_values` AS pav1
ON (`pav1`.`product_id` = `products`.`id`)
JOIN `products_attributes_values` AS pav2
ON (`pav2`.`product_id` = `products`.`id`)
WHERE `category_id` IN ('6', '7', '29', '8', '9', '36')
AND (`pav1`.`attribute_id` = '2' AND `pav1`.`value_id` = '4')
AND (`pav2`.`attribute_id` = '3' AND `pav2`.`value_id` = '11')"

更新了属性组合的查询:

SELECT * FROM products
WHERE category_id IN ('6', '7', '29', '8', '9', '36')
    AND id IN (
        SELECT product_id
        FROM products_attributes_values
        WHERE attribute_id = 2
            AND value_id IN ('4', '5'))
    AND id IN (
        SELECT product_id
        FROM products_attributes_values
        WHERE attribute_id = 3
            AND value_id IN ('11', '62'))

或者

SELECT *
FROM `products`
    JOIN `products_attributes_values` AS pav1 ON (`pav1`.`product_id` = `products`.`id`)
    JOIN `products_attributes_values` AS pav2 ON (`pav2`.`product_id` = `products`.`id`)
WHERE `category_id` IN ('6', '7', '29', '8', '9', '36')
AND (`pav1`.`attribute_id` = '2' AND `pav1`.`value_id` IN ('4', '5'))
AND (`pav2`.`attribute_id` = '3' AND `pav2`.`value_id` IN ('11', '62'))
于 2013-04-14T00:03:31.687 回答