2016-11-11 59 views
0

我在MySql中有三個表格RECIPES,INGREDIENTSRECIPE_INGREDIENTS。現在我想獲取僅包含配料ID的食譜。我簡單的語言,我想搜索食譜,我可以從我有成分。查找只包含給定成分的食譜匹配行

SELECT r.id 
FROM Recipes AS r 
INNER JOIN Recipe_ingredients AS ri ON r.id = ri.recipe_id 
INNER JOIN Ingredients AS i ON i.id = ri.ingredient_id 
WHERE i.id IN (... list of ids here ...) 
GROUP BY r.id 
HAVING COUNT(DISTINCT i.id) <= n -- where n is the number of the ingredient ids 
           -- specified in the list of the where clause 

編輯:如果你想獲得食譜,不要

回答

0

你可以爲了得到配方的IDS有全部或部分的指定成分的使用以下查詢t包含指定列表中未包含的任何成分,則可以使用:

SELECT r.id 
FROM Recipes AS r 
LEFT JOIN Recipe_ingredients AS ri ON r.id = ri.recipe_id 
LEFT JOIN Ingredients AS i ON i.id = ri.ingredient_id 
WHERE i.id NOT IN (... list of ids here ...) 
GROUP BY r.id 
HAVING COUNT(i.id) = 0 
+0

這將顯示包含所有現有成分的食譜 ​​- 但這與實際要求的成分有細微的差異。排除連接實際上是這種情況下需要的 - 所有不包含我沒有的成分的配方。 – Strawberry

+0

@Strawberry我認爲我的查詢返回的食譜只包含*指定的所有*成分ID。 –

+0

我認爲你錯了 - 除此之外,那還*不是你想要的! – Strawberry