2017-08-14 181 views
0

我有三個表一個是產品和第二是appliedFeaturesValue,三是appliedFeaturesMySQL查詢多對多關係

在產品表appliedFeaturesValue有多對多的關係。

ProductID appliedFeaturesValueId 
1   1 
1   2 
2   1 
3   2 

並且在appliedFeaturesValue表中與appliedFeatures具有ManyToOne關係。

appliedFeaturesValue appliedFeaturesId 
    1       70 
    2       88 

我想如果我使用IN子句則不會返回準確的產品數據,其中appliedFeaturesValue.id獲得產品編號1,其中兩個appliedFeaturesValue編號1和2是appliedFeaturesId 70可代表和88

= 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 

我怎麼會得到完全匹配的記錄?

+0

你可以用一些測試數據[在這裏](http://sqlfiddle.com/)創建一個模式的例子並指定合適的輸出嗎? – Serg

回答

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