簡體   English   中英

如何選擇與聯接表中定義的條件匹配的記錄?

[英]How to select records who match criteria defined in a join table?

我有這三個表:

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 2SELECT 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

假設在(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
)

類似於以下內容:

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

將(1,3)換為要包括的功能。

您可以執行以下操作來聯接這些表並獲取所需的數據:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM