2013-03-13 106 views
-1

如果我有一個數據庫可以看作是食譜數據庫,如何選擇我可以用給定成分製作的所有食譜的ID,例如,如果我有成分1和4它會返回3,因爲這是我可以做的唯一配方。選擇多對多關係

將會有大約50種食材和更多的食譜。

我看到幾種可能性,例如使用UNION /幾個連接,但我沒有看到這個問題的簡單解決方案。

Recipes Recipes/Ingredients Ingredients 
    1   1 1     1 
    2   1 2     2 
    3   2 1     3 
       2 3     4 
       2 4 
       3 1 
       3 4 

編輯/

我想到了什麼來解決這個問題:

select recipe_id from Recipes 
where recipe_id in ( 
    select recipe_id from Recipes_Ingredients where ingredient_Id = 1 
    UNION 
    select recipe_id from Recipes_Ingredients where ingredient_Id = 4 
) 

這將導致很長的查詢,我的數據庫是不是真正的成分,但有關的東西,可以有其中50個或更多的這些東西。

+1

[你有什麼試過](http://www.whathaveyoutried.com)? – Kermit 2013-03-13 14:20:43

+0

檢查此鏈接http://stackoverflow.com/questions/349559/sql-how-to-search-a-many-to-many-relationship – Mingebag 2013-03-13 14:21:11

+0

@Aarolama Bluenk我已經搜查,我將能夠解決這個問題UNION聲明。我認爲這不是最好的解決方案,到目前爲止我還沒有找到更好的方法,這就是爲什麼我認爲每天有這方面經驗的人能夠給出一個直接的答案。我不希望有任何疑問或問題,只是解決這些問題的恰當方法。 – 2013-03-13 14:22:26

回答

2

試試這個(我試圖猜測你的名字列):

表食譜:Recipe_id

表Recipes_Ingredients:食譜|成分

SELECT Recipe_id FROM Recipes 
    EXCEPT (
    SELECT DISTINCT Recipes FROM Recipes_Ingredients 
    WHERE Ingredients NOT IN (1,4) 
) 

我會解釋這一點。 如果你想知道「你擁有至少一個成分配方」(這裏:1,4):

SELECT DISTINCT Recipes FROM Recipes_Ingredients 
WHERE Ingredients IN (1,4) 

所以反而是「我不能這樣做,其配方」,因爲你錯過了至少一種成分:

SELECT DISTINCT Recipes FROM Recipes_Ingredients 
WHERE Ingredients NOT IN (1,4) 

然後我們採取所有的那些之外的食譜,你可以這樣做:

SELECT recipe_id FROM Recipes 
    EXCEPT (
    SELECT DISTINCT Recipes FROM Recipes_Ingredients 
    WHERE Ingredients NOT IN (1,4) 
) 
+0

這看起來很有希望,看起來正是我要找的。我正在測試它:) – 2013-03-13 14:46:42

+0

它的工作原理,thx :) – 2013-03-14 17:57:14

+0

不客氣^^ – vaugham 2013-03-15 08:58:07

0

嘗試:

select recipe_id 
from recipes_ingredients 
group by recipe_id 
having count(*)=sum(case when ingredient_id in (1,4) then 1 end)