我正在使用四个表,我将它们称为“products”、“attributes_categories”、“attributes”和“product_has_attributes”。 “products”中的每个产品在“product_has_attributes”中都有很多属性,如下所示:
[product_has_attributes] : product1
attribute_id=1 (Brands->Sony)
attribute_id=4 (Screen size -> 20")
attribute_id=7 (Colors -> Black)
attribute_id=8 (Colors -> White)
products 和 product_has_attributes 在 products.id = product_has_attributes.product_id 上保持连接
一个简单的 SELECT 可以正确地返回每个产品与其属性一样多的次数。
现在,我想选择所有具有以下特征的产品:
product_has_attributes.attribute_id=1 AND
product_has_attributes.attribute_id=4 AND
(product_has_attributes.attribute_id=7 OR
product_has_attributes.attribute_id=8)
但是,正如预期的那样,product_has_attributes.attribute_id 不能同时为 1 AND 4 AND (7 OR 8)...因此不会返回任何记录。
我如何构建 SQL 以便它按照我描述的逻辑返回记录?
谢谢, 乔治
最佳答案
你可以使用这样的东西。它的效率不是很高。
select * from products
where product_id in (
select product_id from product_has_attributes where attribute_id = 1
)
and product_id in (
select product_id from product_has_attributes where attribute_id = 4
)
and product_id in (
select product_id from product_has_attributes where attribute_id in (7, 8)
)
关于MySQL - 1toN,从 table1 中选择具有 table2.attribute=1 和 table2.attribute=2 的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18846198/