2012-02-29 77 views
0

我有兩個SQLite表,配方和配料。我需要從配料列表中找到所有包含2到4個項目的食譜,但是我無法將我的頭部圍繞SQL來完成此項工作。鏈接範圍內的SQL項目

的表是:

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
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 
+0

優秀的,謝謝。我總是使用HAVING條款。 – Echilon 2012-03-01 19:11:49

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 
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 
)