选择多对多的关系

时间:2013-03-13 14:18:48

标签: sql

如果我有一个可以被视为食谱数据库的数据库,我如何选择我可以用给定成分制作的食谱的所有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个或更多这些东西的东西。

2 个答案:

答案 0 :(得分:2)

试试这个(我试着猜测你的列名):

表食谱:Recipe_id

Table 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)  
  )

答案 1 :(得分:0)

尝试:

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