链接范围中的SQL项目

时间:2012-02-29 20:08:33

标签: sql sqlite

我有两个SQLite表,食谱和成分。我需要从成分列表中找到所有含有2到4个项目的食谱,但是我无法理解这一点以使其工作。

表格是:

CREATE TABLE recipes (
    rowidx INTEGER  AUTOINCREMENT,
    RecipeID TEXT(10) NOT NULL PRIMARY KEY,
    Name TEXT(255) NOT NULL
);

 CREATE TABLE Ingredients (
    Recipe TEXT(10) NOT NULL PRIMARY KEY,
    Ingredient TEXT(255) NOT NULL COLLATE NOCASE,
    Measurement TEXT(255) NOT NULL
);

我从一些简单的事情开始,但当我来到'n和n成分'之间时,我已经失去了动力。

SELECT COUNT(*) FROM Recipes 
WHERE RecipeID IN (
    SELECT Recipe FROM Ingredients WHERE Ingredient IN (milk','butter','sugar','flour','egg' ) 
) 

我确信必须有一个相对简单的方法来做到这一点,但它不是点击。

编辑:我实际上最终得到了以下答案的修改版本:

SELECT *,ifnull((SELECT COUNT(i.Ingredient) AS IngredientCount FROM Recipes r LEFT JOIN Ingredients i ON r.RecipeID = i.Recipe WHERE i.Ingredient IN ('flour' ) and r.recipeid = allrecipes.recipeid GROUP BY R.RecipeID),0) AS IngredientCount 
FROM Recipes allrecipes
WHERE IngredientCount BETWEEN 2 AND 4

与原始答案不同,如果食谱不匹配任何成分,并且指定了BETWEEN 0 AND 2,它甚至不会出现在列表中进行排序,因此将被排除。

3 个答案:

答案 0 :(得分:3)

SELECT
    r.Name,
    COUNT(i.Ingredient) AS Ingredients
FROM
    recipes r
    LEFT JOIN ingredients i 
        ON i.Recipe = r.RecipeID
        AND i.Ingredient IN ('milk','butter','sugar','flour','egg')
GROUP BY r.Name
HAVING COUNT(i.Ingredient) BETWEEN 2 AND 4

答案 1 :(得分:1)

SELECT r.* FROM Recipes r
JOIN Ingredients i
  ON r.RecipeID = i.Recipe
WHERE i.Ingredient IN ('milk','butter','sugar','flour','egg')
GROUP BY r.RecipeID
HAVING COUNT(*) BETWEEN 2 AND 4

答案 2 :(得分:0)

同一件事的另一种变体:

SELECT R.*
FROM recipes AS R
WHERE EXISTS(
    SELECT 0
    FROM Ingredients AS I
    WHERE I.Recipe = R.recipeID
      AND I.Ingredient IN ('milk','butter','sugar','flour','egg')
    GROUP BY I.Recipe
    HAVING COUNT(I.Ingredient) BETWEEN 2 AND 4
)