2014-09-04 38 views
-2

得到行我有表recipes2ingredients如何從表

(id, recipe_id, ingredient_id) 

和2的成分,例如1,2。我需要得到所有的recipe_id

where is ingredient_id = 1 and ingredient_id = 2 
+1

因此,是ingredient_id有多個值?這不是一個好的數據庫設計,它違反了第一範式(1NF)。 – Edper 2014-09-04 17:57:35

回答

0

使用having和count以及在哪裏可以找到所有具有這兩種成分的食譜。

SELECT recipe_ID, count(Distinct ingredient_id) 
FROM recipes2ingredients 
WHERE ingredient_ID in (1,2) 
GROUP BY recipe_id 
HAVING count(Distinct ingredient_id) = 2 

使用了不同的計數,因此如果偶爾列出一種成分,我們不會得到誤報。

where子句限制只是那些具有的成分的一個或多個配方和具有子句確保我們只有2

這種方法具有允許兩者where子句的優點和具有計數爲運行時提供的變量,而不必更改查詢結構。

1

假設它在DB服務器上使用;您可以使用。

select distinct r2i1.recipe_id from recipes2ingredients r2i1 
join recipes2ingredients r2i2 
on r2i1.recipe_id = r2i2.recipe_id 
where r2i1.ingredient_id = 1 
and r2i2.ingredient_id = 2; 
+0

這是像OR(1或2)的工作,但我需要 - 1和2 – 2014-09-04 17:56:13

+0

我明白了。我已經更新了答案。 – Abhinav 2014-09-04 17:59:17

+0

只要用戶在每個查詢中不需要可變數量的配料,此功能就可以工作。它不會超過2的極限。 – xQbert 2014-09-04 18:02:53