2011-01-05 84 views
0

這似乎是這將是簡單的,但由於某種原因,我不能讓這個做我想做什麼?在連接表搜索多個標準

我有一個食譜網站,我想成爲能夠根據是否包含多種成分來搜索食譜。我有兩張桌子,裏面有所有食譜信息,第二張桌子上還有食材。這是我迄今爲止的,但它不檢索任何記錄。任何幫助,將不勝感激。謝謝!

SELECT recipe.ID, recipe.Title, recipe.Photo FROM ingredient 
LEFT JOIN recipe ON ingredient.Recipe_ID = recipe.ID 
WHERE (ingredient.Description = 'egg' AND ingredient.Description = 'sugar' AND ingredient.Description = 'salt') 
GROUP BY recipe.ID 
+0

谷歌「關係部門」。 – onedaywhen 2011-01-06 09:21:07

回答

1

你得到任何結果,因爲在你的WHERE子句中AND使它成爲一個不可能的條件,因爲你不會有一個排,其中描述是所有這些值同時

0
select recipe.ID, recipe.Title, recipe.Photo 
from(
    select recipe.ID, recipe.Title, recipe.Photo 
    ,count(ingredient.description) as num_ingredients 
    from ingredient left join recipe 
    on ingredient.recipe_id=recipe.ID 
    group by 1,2,3 
    )ingred_count 
where num_ingredients>=2; 

如果你想看看有多種成分的食譜,應該這樣做。否則,如果您想要每個配方的配料數量,請使用子查詢。

0

看起來您的ingredient表包含Recipe_ID。這實際上會使這個查詢非常容易,因爲您只需要查看哪個Recipe_ID發生在多行中。

SELECT I.recipe_id 
FROM ingredient I 
WHERE COUNT(I.description) > 0 
GROUP BY I.recipe_id 

將給出所有這些食譜的ID。如果你想不僅僅是ID越多,你會需要一個連接

SELECT R.* 
FROM ingredient I 
INNER JOIN recipe R on I.recipe_id = R.id 
WHERE COUNT(I.description) > 0 
GROUP BY I.recipe_id 

我強烈建議你看看到許多一對多的表,你會說出類似recipe_to_ingredient。這將有recipe_id/ingredient_id對這樣,你有一個表recipe,表ingredient和一張桌子recipe_to_ingredient(也許達?)

2

如果你想有至少這3種成分的所有食譜,然後嘗試:

SELECT recipe.ID, recipe.Title, recipe.Photo FROM recipe 
WHERE recipe.ID in (
    SELECT Recipe_ID 
    FROM ingredient 
    WHERE ingredient.Description in ('egg', 'sugar', 'salt') 
    HAVING count(distinct ingredient.Description) = 3 
    GROUP BY Recipe_ID 
) 
+0

這解決了。非常感謝您花時間回答! – 2011-01-06 14:20:46

+0

@Jon:太好了。你可以'接受'這個答案,而不是勾選它旁邊的複選框。 – Gerrat 2011-01-06 14:36:43