Mysql 如何选择符合联接表中定义的条件的记录?

Mysql 如何选择符合联接表中定义的条件的记录?,mysql,Mysql,我有三张桌子: products TABLE: id:integer name:string features TABLE: id:integer name:string features_products TABLE: product_id:integer feature_id:integer features\u products表告诉我每个产品都有哪些功能。例如: product_id feature_id 1 3 1 5 3

我有三张桌子:

products TABLE:
id:integer
name:string

features TABLE:
id:integer
name:string

features_products TABLE:
product_id:integer
feature_id:integer
features\u products表
告诉我每个产品都有哪些功能。例如:

product_id feature_id
   1         3
   1         5
   3         4
告诉我产品1有功能3和5,产品3有功能4,而且产品2(如果存在)没有功能


我的问题是,如何从产品表中选择具有确定特征的所有产品?例如,
选择具有功能3和功能5的产品
,或
选择具有功能2的产品
类似于以下内容:

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

将(1,3)替换为要包含的功能。

类似于以下内容:

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

将(1,3)替换为要包含的功能。

要为同时具有功能3和功能5的产品选择所有产品ID,请执行以下操作:

SELECT product_id
FROM features_products
WHERE feature_id IN (3, 5)
GROUP BY product_id
HAVING COUNT(*) = 2
这假设(产品标识、功能标识)上存在唯一性约束。如果要从product表中获取整行,请在子查询中使用:

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
)

要为同时具有功能3和功能5的产品选择所有产品ID,请执行以下操作:

SELECT product_id
FROM features_products
WHERE feature_id IN (3, 5)
GROUP BY product_id
HAVING COUNT(*) = 2
这假设(产品标识、功能标识)上存在唯一性约束。如果要从product表中获取整行,请在子查询中使用:

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

您可以执行以下操作来联接这些表并获取所需的数据:

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

我编辑的产品的特点。谢谢。我编辑的产品。谢谢,好的。这很有效。非常感谢。在接受之前,我只想阅读其他选项和优化。好的。这很有效。非常感谢。在接受之前,我只想阅读其他选项和优化。