简体   繁体   English

如何选择与联接表中定义的条件匹配的记录?

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

I have this three tables: 我有这三个表:

products TABLE:
id:integer
name:string

features TABLE:
id:integer
name:string

features_products TABLE:
product_id:integer
feature_id:integer

The features_products TABLE tells me which features have each product. features_products TABLE告诉我每个产品具有哪些功能。 For example: 例如:

product_id feature_id
   1         3
   1         5
   3         4

tells me the product 1 has features 3 and 5 and product 3 have feature 4, also, product 2 (if exists) doesn't have features. 告诉我产品1具有功能3和5,产品3具有功能4,并且产品2(如​​果存在)不具有功能。

My question is, how can I SELECT all the products from the products TABLE wich have determinated features? 我的问题是,如何从具有确定功能的表中SELECT所有产品? For example, SELECT products which have features 3 AND 5 , or SELECT products which have feature 2 例如, SELECT products which have features 3 AND 5 SELECT products which have feature 2SELECT products which have feature 2

To select all the product ids for products which have both features 3 and 5: 要选择同时具有功能3和功能5的产品的所有产品ID:

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

This assumes that there is a uniqueness contraint on (product_id, feature_id). 假设在(product_id,feature_id)上存在唯一性约束。 If you want the entire row from the product table then use this in a subquery: 如果要从产品表中获取整行,请在子查询中使用它:

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
)

Something similar to this: 类似于以下内容:

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

swap out the (1,3) for the features you want to include. 将(1,3)换为要包括的功能。

You could do the following the join those tables and get the data you need: 您可以执行以下操作来联接这些表并获取所需的数据:

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