加入三个表,查询在SQLite

时间:2016-10-02 10:58:32

标签: android sqlite

我正在构建一个按成分搜索食谱的应用程序。我有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分钟或以上的配方。

1 个答案:

答案 0 :(得分:2)

尝试

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