I have two SQLite tables, recipes and ingredients. I need to find all of the recipes which have between 2 and 4 items from a list of ingredients but I can’t get my head round the SQL to make this work.
The tables are:
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
);
I started with something simple, but ran out of steam when I came to the ‘between n and n ingredients’ part.
SELECT COUNT(*) FROM Recipes
WHERE RecipeID IN (
SELECT Recipe FROM Ingredients WHERE Ingredient IN (milk','butter','sugar','flour','egg' )
)
I’m sure there must be a relatively simple way to do this but it’s not clicking.
EDIT: I actually ended up with a modified version of the answer below:
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
Unlike the original answer, if a recipe matches no ingredients, and BETWEEN 0 AND 2 is specified, it won’t even appear in the list for sorting, so will be excluded.
1 Answer