Select 多对多关系
Select on many to many relation
我有两个实体 Product(int id ID)
和 Attribute(int id ID)
。每个产品都可以有多个具有自定义值的属性,所以我有一个 ProductAttribute(int product_id, int attribute_id, int value)
.
我想搜索具有值 x 的属性 1 和值 y 的属性 2 以及...的产品。
这可能吗?如何?或者我应该改变关系图?
如果重要的话,我正在使用 MySQL 5.7。
您可以使用聚合和 having
:
select product_id
from ProductAttribute
where (attribute_id, value) in ( (1, 2), (2, 3), (3, 4))
group by product_id
having count(*) = 3;
“3”是正在比较的列表中的属性数。
我有两个实体 Product(int id ID)
和 Attribute(int id ID)
。每个产品都可以有多个具有自定义值的属性,所以我有一个 ProductAttribute(int product_id, int attribute_id, int value)
.
我想搜索具有值 x 的属性 1 和值 y 的属性 2 以及...的产品。
这可能吗?如何?或者我应该改变关系图?
如果重要的话,我正在使用 MySQL 5.7。
您可以使用聚合和 having
:
select product_id
from ProductAttribute
where (attribute_id, value) in ( (1, 2), (2, 3), (3, 4))
group by product_id
having count(*) = 3;
“3”是正在比较的列表中的属性数。