2010-07-05 47 views
1

我有这三个表:如何选择符合连接表中定义条件的记录?

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所有的产品从产品TABLE具有确定的功能?例如,SELECT products which have features 3 AND 5,或SELECT products which have feature 2

+0

features_products我编辑。谢谢。 – 2010-07-05 18:59:07

回答

5

要选择具有这两种功能3和5的产品的所有产品ID:

SELECT product_id 
FROM features_products 
WHERE feature_id IN (3, 5) 
GROUP BY product_id 
HAVING COUNT(*) = 2 

这假定有上(产品,FEATURE_ID)唯一性contraint。如果你想从产品表中的整行,然后在子查询中使用:

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 
) 
+0

好的。这工作。谢谢。我只想在接受它之前阅读其他选项和优化。 – 2010-07-05 19:00:03

0

事情与此类似:您要包括的特征

select * from product 
where id in (select product_id from feature_products where feature id in (1,3)) 

掉了(1,3)。

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 
相关问题