2016-12-01 82 views
1

我试图选择所有包含给定数量配料的配方。我能找到基于一个给定的所有食谱recipe_id :SQL - 多对多查询

SELECT name 
FROM recipe 
INNER JOIN recipe_ingredient 
ON recipe.recipe_id = recipe_ingredient.recipe_id 
WHERE recipe_ingredient.recipe_id = ? 

,但我有麻烦搞清楚查询应该是什么时,我正在寻找的食谱等,其包含比含有较多多于一种特定成分。例成分A和B.成分

我的表是这样的:

ingredient 
    -ingredient_id 
    -name 

recipe_ingredient 
    -recipe_ingredient 
    -ingredient_id 
    -recipe_id 


recipe 
    -recipe_id 
    -name 

我会是关于如何解决这个问题的任何想法很开心! 谢谢。通过having子句

+1

还有就是在这里进行区分。你是否想要所有有多种成分的食谱,而不管这些成分是哪一种?或者你想要所有包含特定成分的食谱?从你的问题不清楚,但有覆盖 – EoinS

+0

的答案你是对的,我的问题还不够清楚。对不起。我正在寻找所有含有特定成分的食谱! – ArtemisUser

+0

好的 - 我根据这个评论更新了我的回答 – kbball

回答

-1

使用组和

SELECT name 
FROM recipe 
INNER JOIN recipe_ingredient 
ON recipe.recipe_id = recipe_ingredient.recipe_id 
GROUP BY name 
HAVING count(1) > 1 
+0

你的小组应该在名字上。我很确定这会抛出一个错误,因为写了 – kbball

+0

是的,我在想同样的事情,只是为了简化查询,谢谢:) –

0

您的查询将是这个样子

Your query will look something like this 

SELECT name, count(*) 
FROM recipe 
INNER JOIN recipe_ingredient 
ON recipe.recipe_id = recipe_ingredient.recipe_id 
GROUP BY name 
HAVING count(*) > 1 
0

为了匹配IN条款的所有元素,你需要确保你只选择有count的食谱,它与您列表中的成分总数相匹配:

SELECT name 
FROM recipe 
INNER JOIN recipe_ingredient 
ON recipe.recipe_id = recipe_ingredient.recipe_id 
WHERE recipe_ingredient.ingredient_id IN (ID1, ID2, ID3) --list of ingredient IDs 
Group By Name 
Having Count(*) = 3 --# of Ingredients you have chosen 

祝你好运找到这食谱将与配料工作,你必须提供

Here is a functional example

+0

当我改变最后一行'WHERE recipe_ingredient。recipe_id IN(ID1,ID2,ID3)'到'WHERE recipe_ingredient.ingredient_id IN(ID1,ID2,ID3)'它给我所有包含至少一个给定ID的食谱!所以这对我来说是朝着正确方向迈出的一大步。但现在我的问题是如何获得至少包含所有给定成分的食谱,而不仅仅是给定成分的子集。 – ArtemisUser

+0

@ArtemisUser感谢您指出它应该是'ingredient_id'。我只是更新了答案,以确保您匹配列表中的所有元素 – EoinS

-1

只需使用ORwhere。 像这样

$query = "SELECT name 
FROM recipe 
INNER JOIN recipe_ingredient 
ON recipe.recipe_id = recipe_ingredient.recipe_id 
WHERE recipe_ingredient.recipe_id = ? OR recipe_ingredient.recipe_id = ?"; 
0

IF寻找特定的成分,你可以做一个预查询做所有你感兴趣的组分组成的联盟。加入,为每个配方成分表,并确保所有成分占了。这是由小组处理,并有计数=你正在寻找的成分数量。

我做了这个基于成分名称的例子。如果您已经知道实际配料ID(这将更准确,例如基于网络并且您有用户选择的ID),只需将加入条件更改为配料ID,而不仅仅是配料的描述。

SELECT 
     r.name, 
     r.recipe_id 
    from 
     (SELECT 'Milk' as Ingredient 
      UNION select 'Eggs' 
      UNION select 'Butter') as Wanted 
     JOIN recipe_ingredient ri 
      ON Wanted.Ingredient = ri.recipe_ingredient 
      JOIN Recipe r 
       ON ri.Recipe_id = r.id 
    group by 
     ri.recipe_id 
    having 
     COUNT(*) = 3 

在这种情况下,牛奶,黄油,鸡蛋和最终计数= 3