【问题标题】:Find the number of recipes possible from given ingredients? SQL Query从给定的成分中找出可能的食谱数量? SQL 查询
【发布时间】:2021-02-18 13:48:39
【问题描述】:

我正在努力找出查询(真的是画一个空白)以获取可以从可用原料库存中创建的所有食谱。

创建的表是:

CREATE TABLE recipe(id int, name varchar(25));  
CREATE TABLE ingredients(id int, name varchar(25), stock int);
CREATE TABLE recipeingredients(recipe_id int, ingredients.id int, amount int);

数据库中的记录会是这样的

Recipe
ID | Name        |
1  | Brown Bread |
2  | White Bread |

Ingredients
ID | Name        | Stock |
1  | White Flour | 2     |
2  | Wheat Flour | 1     |
3  | Yeast       | 17    |
4  | Water       | 12    |

RecipeIngredients
RecipeID | IngredientID | Amount |
1        | 1            | 1      |
1        | 3            | 4      |
1        | 4            | 8      |
2        | 2            | 1      |
2        | 3            | 4      |
2        | 4            | 8      |

所以结果会是这样的

Name        | Count |
White Bread | 1     |
Wheat Bread | 1     |

这可能很简单,但现在对 SQL 很生疏。

【问题讨论】:

    标签: sql database h2


    【解决方案1】:
    select recipe
    , min([count]) as 'count'
    
    from (
        select r.name as recipe
        , i.name as ingredient
        , i.stock / ri.amount as 'count'
    
        from recipeingredients ri
          inner join ingredients i on i.id = ri.ingredients_id
          inner join recipe r on r.id = ri.recipe_id
    ) q
    
    group by recipe
    

    【讨论】:

    • 看起来应该可以了。只是在第 3 行出现语法错误,不确定如何修复。 “您的 SQL 语法有错误;似乎错误就在附近:'[count]) as 'count' from (select r.name as recipe as' at line 3"
    • 啊,我发现了语法问题。 h2 不喜欢 'count' 周围的引号。谢谢,这很好用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    相关资源
    最近更新 更多