MySQL - 1toN,从 table1 中选择具有 table2.attribute=1 和 table2.attribute=2 的项目

标签 mysql subquery

我正在使用四个表,我将它们称为“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/

相关文章:

sql - 子查询是重用变量的唯一选择吗?

PHP/MySQL 函数导致其他函数停止工作

Mysql从不同的表中添加列

Mysql工作台系统错误: 0

sql - 新手问题 : Problem with results, sql, join, where, "<"操作符

mysql - 左连接与子选择 - 右表列不显示

mysql - 如何根据键查找特定列的值之间的差异?

java - 如何显示发布到我的论坛中的答案数量?

mysql - SUM 结果的子查询 AVG

sql - 错误: 'duplicate key value violates unique constraint' even when checking with 'where not in'