繁体   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