我对电子商务网站产品过滤器的查询有问题。
我有这样的EAV数据模型:
products [id, title....]
attributes [id, name]
attributes_entity [product_id, attribute_id, value_id]
attributes_values [id, value]
我的查询:
SELECT
products.id,
products.title
FROM
products
WHERE products.id IN
(
SELECT attributes_entity.product_id FROM attributes_entity INNER JOIN
attributes ON attributes_entity.attribute_id=attributes.id INNER JOIN
attributes_values ON attributes_entity.value_id=attributes_values.id
WHERE
(
(attributes.name="Memory" AND attributes_values.value="16GB")
>> AND
(attributes.name="Color" AND attributes_values.value="Gold")
)
)
AND products.category_id = :category_id
问题是,当我在(attributes.name="Memory"AND attributes_values.value="16GB")子查询之间使用>>AND时,我得到0个结果,但当我使用OR时,它会给我更多我需要的结果,而这些结果与这2个条件无关。
例如,当我收到请求时:"内存=16GB,颜色=黑色"。我预计会得到iPhone 5 16BG黑色,而不是所有(金色、太空灰等)带有16GB 的iPhone
我正在寻找查询示例,最好是描述它的工作原理。
谨致问候,Anton
您的子查询应该是这样的:
SELECT
attributes_entity.product_id
FROM
attributes_entity INNER JOIN attributes
ON attributes_entity.attribute_id=attributes.id
INNER JOIN attributes_values ON
attributes_entity.value_id=attributes_values.id
WHERE
(attributes.name="Memory" AND attributes_values.value="16GB")
OR
(attributes.name="Color" AND attributes_values.value="Gold")
GROUP BY
attributes_entity.product_id
HAVING
COUNT(DISTINCT attributes.name)=2
此解决方案使用GROUP BY子查询。您必须使用OR,因为属性不能在同一行同时为Memory和Color,它们可以都为true,但在不同的行上。COUNT(DISTINCT attributes.name)统计Color或Memory的数字属性,如果是2,则至少有1行第一个条件为true,1行另一个条件也为true。