我是一个很好的人,我有两个表:"产品"和"产品属性".
这是一些虚构的数据(实际的东西涉及更多的表格)
产品表:
product_id | product_name
10 | aaa
11 | bbb
12 | ccc
Run Code Online (Sandbox Code Playgroud)
产品属性表:
attribute_id | product_id
21 | 10
23 | 10
24 | 10
21 | 11
24 | 11
21 | 12
25 | 12
Run Code Online (Sandbox Code Playgroud)
每个产品都有多个可能的属性.我有一个属性ID列表,(21,10,25)我需要选择其属性是该列表子集的所有产品.
是否可以在一个查询中执行此操作?
当我过滤(21,24)所需的输出是仅返回产品11(bbb)
当我过滤(21,23,24)时,所需的输出是返回产品10和11.
当我过滤(21)时,所需的输出是不返回(因为所有产品至少有一个其他属性).
如果您假装过滤器在表中:
select *
from product p
where not exists (
select 1
from attributes a
where a.product_id = p.product_id
and not exists(
select 1
from filter f
where f.id_attribute = a.id_attribute))
Run Code Online (Sandbox Code Playgroud)
如果它在构造的查询中:
select *
from product p
where not exists (
select 1
from attributes a
where a.product_id = p.product_id
and attribute_id not in (<list>))
Run Code Online (Sandbox Code Playgroud)
这是我的头脑,所以可能有错别字.