我有一个包含产品和一组属性的类别。 这些属性是“形状”和“直径”。
当我打开一个没有应用过滤器的类别时,我会得到以下查询的产品:
"SELECT * FROM `products`
WHERE `category_id`
IN ('6', '7', '29', '8', '9', '36')"
然后我点击属性“Diameter”(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')"
我得到了我所需要的,所有珠子都有“直径8mm” 然后我想更多地过滤我的产品并点击属性“Shape”(id = 3),其值为“Round”(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毫米和圆形的珠子。 另外所有过滤器都可以正常工作当我想像上面的例子中那样混合它时,它就无法工作。 我如何修改查询以完成工作?
感谢。
更新
我想将一个属性的多个值与另一个属性中的一个或多个组合在一起。
例如,我想得到直径为8mm(id = 4)或直径(id = 2)10mm(id = 5)和圆形的形状(id = 3)的珠子(id = 2)(id = 11) )或形状(id = 3)分面(id = 62)
所以最后我想要得到圆形或刻面形状的8毫米或10毫米珠子。
答案 0 :(得分: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'))