【问题标题】:JOINing three tables, query not working as expected in SQLite加入三个表,查询在 SQLite 中没有按预期工作
【发布时间】:2016-10-03 18:13:57
【问题描述】:

我正在构建一个按成分搜索食谱的应用。我有 5 张桌子:

食谱

RecipeId | RecipeTitle | Directions | PrepTime | CookTime

成分

IngredientId | IngredientName

类别

CategoryId | CategoryName

RecipeIngredient 联结表(多对多)

RecipeId | IngredientId | Quantity | UOM | Comments

RecipeCategory 联结表(多对多)

RecipeId | CategoryId

我想做的是让用户选择成分、类别和时间,应用程序将搜索适合用户输入的食谱。在我的应用程序中实现之前,我正在测试它如何使用 DB Browser for SQLite 工作,但它没有按预期工作。

这是我尝试过的最新查询(当然我假设用户在这里输入,他们不受他们可以选择的成分和类别数量的限制):

SELECT RecipeTitle, COUNT(RecipeTitle) AS Ing FROM Recipe

JOIN RecipeIngredient ON Recipe.RecipeId = RecipeIngredient.RecipeId
JOIN RecipeCategory ON Recipe.RecipeId = RecipeCategory.RecipeId

WHERE
    RecipeIngredient.IngredientId = 
    (SELECT Ingredient.IngredientId FROM Ingredient
    WHERE Ingredient.IngredientName = "olive oil")
OR
    RecipeIngredient.IngredientId = 
    (SELECT Ingredient.IngredientId FROM Ingredient
    WHERE Ingredient.IngredientName = "beef")
OR
    RecipeIngredient.IngredientId = 
    (SELECT Ingredient.IngredientId FROM Ingredient
    WHERE Ingredient.IngredientName = "parsley")
AND
    RecipeCategory.CategoryId = 
    (SELECT Category.CategoryId FROM Category
    WHERE Category.CategoryName = "Dinner")
AND
    Recipe.PrepTime + Recipe.CookTime < 35 -- In minutes

GROUP BY RecipeTitle
ORDER BY Ing DESC -- Orders results by recipes that have the most out of the ingredients the user chose, with less relevant recipes at the bottom

以下是我遇到的问题:

  • 我希望 COUNT(RecipeTitle) 计算结果中每个食谱中选择的成分的数量,但它也计算类别。
  • 类别和时间搜索不起作用。它确实显示了包含所选成分的食谱,但也显示了不是Dinner 并且需要总时间为 35 分钟或以上的食谱。

【问题讨论】:

    标签: android sqlite


    【解决方案1】:

    试试

    SELECT RecipeTitle, COUNT(Ingredient.IngredientId) AS Ing 
    FROM Recipe
    JOIN RecipeIngredient ON Recipe.RecipeId = RecipeIngredient.RecipeId
    JOIN RecipeCategory ON Recipe.RecipeId = RecipeCategory.RecipeId
    JOIN Ingredient ON RecipeIngredient.IngredientId = Ingredient.IngredientId 
    JOIN Category ON CategoryCategoryId = RecipeCategory.CategoryId
    WHERE Ingredient.IngredientName IN ('olive oil', 'beef', 'parsley')
    AND Category.CategoryName = 'Dinner'
    AND (Recipe.PrepTime + Recipe.CookTime) < 35
    GROUP BY RecipeTitle
    ORDER BY Ing DESC
    

    【讨论】:

    • 它告诉我没有Category.CategoryName 这样的列,但后来我加入了Category 表,它现在正在工作!谢谢你。但我有个问题。可以加入4张桌子吗?这是一种好的做法吗?
    • 好的,谢谢您的帮助。我也应该像我一样加入 Category 表,对吗?
    • 是的,我只是忘了添加它。现在更新了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    相关资源
    最近更新 更多