【问题标题】:Recipe Database, search by ingredients配方数据库,按成分搜索
【发布时间】:2018-05-07 06:54:30
【问题描述】:

我的数据库中有以下 3 个表,但在查询它们以获得我想要的结果时遇到了一些问题。我正在尝试按成分搜索食谱。

SQL 小提琴:Fiddle

这是我的表格: 成分

+---------------+---------+
| ingredient_id | name    |
+---------------+---------+
|             1 | tomato  |
|             2 | onion   |
|             3 | rice    |
|             4 | chicken |
|             5 | beef    |
|             6 | noodles |
|             7 | salt    |
+---------------+---------+

食谱

+-----------+------------------+
| recipe_id | name             |
+-----------+------------------+
|         1 | tomato goodness  |
|         2 | meat deluxe      |
|         3 | chicken surprise |
+-----------+------------------+

成分索引

+-----------+---------------+
| recipe_id | ingredient_id |
+-----------+---------------+
|         1 |             1 |
|         1 |             5 |
|         1 |             7 |
|         2 |             5 |
|         2 |             6 |
|         2 |             7 |
|         3 |             4 |
|         3 |             3 |
|         3 |             7 |
+-----------+---------------+

我想要实现的是过滤我可以使用指定成分制作的所有食谱。问题来了:

这个查询:

select DISTINCT r.name
from 
    recipes r
    inner join ingredient_index i
    on i.recipe_id = r.recipe_id
where i.ingredient_id IN (2, 7, 5);

给我错误的结果,因为我没有足够的原料来制作任何食谱,但我仍然得到一个我可以制作所有这些的结果。发生这种情况是因为 recipe_idIngredient_Index 表中重复。

如果有任何帮助,我将不胜感激。

【问题讨论】:

  • 要么计算成分以使它们都存在,要么检查没有缺少成分。
  • 你能告诉我怎么做吗?我很难弄清楚这一点。
  • 这是一个非常有趣的问题,我想我会把它放在我学生的下一个测试中}:-)
  • @Cynical,还添加一个预计会找到的配方。

标签: mysql sql database filter


【解决方案1】:

正如 jarlh 所说,检查没有缺少成分:

select DISTINCT r.name
from recipes r
where not exists (
select 1 from ingredient_index i where r.recipe_id=i.recipe_id and i.ingredient_id not in (2,5,7)
)

【讨论】:

  • jarih 说的,不是我 :)。无论如何,感谢你们俩的超快响应和满足我的需求。
【解决方案2】:

我的遵循 jarlh 给出的其他建议,并检查是否所有成分都可用:

select distinct a.name
from (select r.name, count(*) as ing_available
      from 
          recipes r
          inner join ingredient_index i
          on i.recipe_id = r.recipe_id
      where i.ingredient_id IN (1, 7, 5)
      group by r.recipe_id) 
as a join 
      (select r.name, count(*) as ing_required
      from 
          recipes r
          inner join ingredient_index i
          on i.recipe_id = r.recipe_id
      group by r.recipe_id)
as p 
on p.ing_required = a.ing_available

【讨论】:

    【解决方案3】:

    另一种方式:

    select r.name
    from recipes r
       join ingredient_index i on i.recipe_id = r.recipe_id
    where i.ingredient_id IN (2, 7, 5)
    group by r.name
    having count(i.ingredient_id) = 3
    

    【讨论】:

    • 我以前试过这个。它不起作用然后我有不同数量的成分的食谱。
    • 好吧,因为我打字太慢了,当其他好答案发布时,我并没有真正找到完成它的灵感。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多