首先,您的查询可以大大简化,因为您不需要外部查询。以下是完全相同的:
SELECT r.recipeTitle AS recipe
FROM recipeIng il, Ingredient i, Recipe r
WHERE (il.ingredientID = i.ingredientID)
AND (il.recipeID = r.recipeID)
AND (i.ING LIKE '%cheese%' AND i.ING LIKE '%salmon%')
其次,您不需要所有这些括号。
SELECT r.recipeTitle AS recipe
FROM recipeIng il, Ingredient i, Recipe r
WHERE il.ingredientID = i.ingredientID
AND il.recipeID = r.recipeID
AND i.ING LIKE '%cheese%'
AND i.ING LIKE '%salmon%'
第三,您应该 INNER JOIN 表以使它们之间的关系更清晰:
SELECT r.recipeTitle AS recipe
FROM recipeIng il JOIN
Ingredient i ON il.ingredientID = i.ingredientID JOIN
Recipe r ON il.recipeID = r.recipeID
WHERE i.ING LIKE '%cheese%'
AND i.ING LIKE '%salmon%'
至此,问题应该很清楚了——有 2 种可能的可能性,2 种可能性大于 1 种可能性。
1) 您的ING
字段将配方的所有成分存储在一个字段中。如果是这种情况,那么您没有一个食谱,其成分需要奶酪和鲑鱼。
2) 您的ING
字段每行仅存储 1 种成分。Cheese
但是,您要求的是包含和的单行Salmon
。这不是您的意图,因此查询是错误的。
-- SELECT ALL RECIPES USING CHEESE *OR* SALMON
SELECT r.recipeTitle AS recipe
FROM recipeIng il JOIN
Ingredient i ON il.ingredientID = i.ingredientID JOIN
Recipe r ON il.recipeID = r.recipeID
WHERE i.ING LIKE '%cheese%'
AND i.ING LIKE '%salmon%'
-- SELECT ALL RECIPES USING CHEESE *AND* SALMON
SELECT r.recipeTitle AS recipe
FROM recipeIng il JOIN
Ingredient iCheese
ON il.ingredientID = i.ingredientID
AND i.ING LIKE '%cheese%' JOIN
Ingredient iSalmon
ON il.ingredientID = i.ingredientID
AND i.ING LIKE '%salmon%' JOIN
Recipe r ON il.recipeID = r.recipeID
请注意,以上仅为示例 - 在不了解您的架构的情况下,这些只是提示和建议 :)