mysql查询ManyToMany Relation

时间:2017-08-14 07:53:05

标签: mysql phpmyadmin

我有三个表,一个是product,第二个是appliedFeaturesValue,第三个是appliedFeatures

在Product表中,applyFeaturesValue具有ManyToMany关系。

ProductID appliedFeaturesValueId
 1          1
 1          2
 2          1
 3          2

并且在appliedFeaturesValue表中与appliedFeatures具有ManyToOne关系。

appliedFeaturesValue    appliedFeaturesId
    1                          70
    2                          88

我想得到产品ID 1,其中appliedFeaturesValue Id 1和2都代表appliedFeaturesId 70和88。

如果我正在使用IN子句,则不会返回确切的产品数据,其中appliedFeaturesValue.id = 1 AND appliedFeaturesValue.id = 2.

如果我使用AND子句,则找不到结果。

这是我使用AND子句的原始查询,其中找不到结果: -

SELECT p0_ FROM Product p0_ INNER JOIN product_applied_features_value p2_ ON p0_.id = p2_.product_id INNER JOIN applied_features_value a1_ ON a1_.id = p2_.applied_features_value_id WHERE p0_.status = 1 AND a1_.applied_features_id = 70 AND a1_.applied_features_id = 88 ORDER BY p0_.id DESC

这是我使用IN子句的查询: -

SELECT p0_ FROM Product p0_ INNER JOIN product_applied_features_value p2_ ON p0_.id = p2_.product_id INNER JOIN applied_features_value a1_ ON a1_.id = p2_.applied_features_value_id WHERE p0_.status = 1 AND a1_.applied_features_id IN (70,88) ORDER BY p0_.id DESC

我将如何获得完全匹配的记录?

1 个答案:

答案 0 :(得分:0)

尝试以下查询,这可以帮助您。

SELECT product.* FROM Product product 
INNER JOIN product_applied_features_value prodAppFeatures ON product.appliedFeaturesValueId = prodAppFeatures.id
INNER JOIN applied_features_value appFeatures ON appFeatures.id = prodAppFeatures.applied_features_value_id 
WHERE product.status = 1 AND 
    appFeatures.applied_features_id = 70 AND a1_.applied_features_id = 88 ORDER BY product.id DESC