2010-07-05 50 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 
相關問題