我有这三张桌子:
products TABLE:
id:integer
name:string
features TABLE:
id:integer
name:string
features_products TABLE:
product_id:integer
feature_id:integer
features_products TABLE
告诉我每个产品有哪些功能。例如:
product_id feature_id
1 3
1 5
3 4
告诉我产品1具有功能3和5,产品3具有功能4,产品2(如果存在)没有功能。
我的问题是,我如何SELECT
产品中的所有产品都具有确定的功能?例如,SELECT products which have features 3 AND 5
或SELECT products which have feature 2
答案 0 :(得分:5)
为具有功能3和5的产品选择所有产品ID:
SELECT product_id
FROM features_products
WHERE feature_id IN (3, 5)
GROUP BY product_id
HAVING COUNT(*) = 2
这假设(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
)
答案 1 :(得分:0)
类似的东西:
select * from product
where id in ( select product_id from feature_products where feature id in ( 1,3 ) )
将(1,3)替换为您要包含的功能。
答案 2 :(得分:0)
您可以执行以下操作来连接这些表并获取所需的数据:
SELECT *
FROM products p JOIN features_products fp ON p.id = fp.product_id
JOIN features f ON f.id = fp.feature_id
WHERE f.id = 3 OR f.id = 5