我有这三个表:
products TABLE:
id:integer
name:string
features TABLE:
id:integer
name:string
features_products TABLE:
product_id:integer
feature_id:integer
Run Code Online (Sandbox Code Playgroud)
该features_products TABLE告诉我哪些功能有每个产品.例如:
product_id feature_id
1 3
1 5
3 4
Run Code Online (Sandbox Code Playgroud)
告诉我产品1具有特征3和5,产品3具有特征4,产品2(如果存在)没有特征.
我的问题是,我怎样才能SELECT从产品TABLE中获得具有确定功能的所有产品?例如SELECT products which have features 3 AND 5,或SELECT products which have feature 2
要为具有功能3和5的产品选择所有产品ID:
SELECT product_id
FROM features_products
WHERE feature_id IN (3, 5)
GROUP BY product_id
HAVING COUNT(*) = 2
Run Code Online (Sandbox Code Playgroud)
这假定在(product_id,feature_id)上存在唯一性约束.如果您想要产品表中的整行,请在子查询中使用它:
SELECT *
FROM products
WHERE product_id IN (
SELECT product_id
FROM features_products
WHERE feature_id IN (3, 5)
GROUP BY product_id
HAVING COUNT(*) = 2
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
198 次 |
| 最近记录: |