SQL - 多对多查询

时间:2016-12-01 16:21:11

标签: mysql sql

我正在尝试选择包含给定数量成分的所有食谱。我能够根据给定的recipe_id找到所有食谱 用:

const

但是当我在寻找包含多于一种特定成分的配方时,我无法弄清楚查询应该是什么样子。例如成分A和成分B.

我的表格如下:

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

对于如何解决这个问题,我会非常高兴! 感谢。

5 个答案:

答案 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

答案 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

答案 2 :(得分:0)

如果寻找特定的成分,你可以做一个预先查询,做一个你感兴趣的所有成分的联合。加入每个食谱的成分表,并确保所有成分都被考虑在内。这由小组处理,并且具有count =你正在寻找的成分的数量。

我根据成分的名称做了这个例子。如果您拥有/知道实际成分ID(这将更准确,例如基于网络,并且您拥有用户选择的ID),只需将连接条件更改为成分ID,而不仅仅是成分的描述。 / p>

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。

答案 3 :(得分:-1)

使用group by和having子句

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

答案 4 :(得分:-1)

只需对OR使用where即可。 喜欢这个

$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 = ?";