1

我正在使用四个表,我将它们称为“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 以返回我描述的逻辑中的记录?

谢谢你,乔治

4

1 回答 1

0

你可以使用这样的东西。它的效率不是很高。

 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)
 )
于 2013-09-17T09:40:21.277 回答