我编写了一个查询,该查询创建了一个新的临时行,其频率显示为id,并且我需要删除所有低于我的频率过滤器要求4的项目。代码按计划工作,直到我添加了where子句(如下)。无法在通常的位置添加where子句的原因是什么?
SELECT RecipeTitle, COUNT(recipes.RecipeID) AS ingredientsNeeded FROM recipes
INNER JOIN recipe_ingredients ON recipe_ingredients.RecipeID = recipes.RecipeID
GROUP BY recipes.RecipeID
ORDER BY ingredientsNeeded ASC
返回
Calzone | 3
Hot dog | 2
等
SELECT RecipeTitle, COUNT(recipes.RecipeID) AS ingredientsNeeded FROM recipes
INNER JOIN recipe_ingredients ON recipe_ingredients.RecipeID = recipes.RecipeID
GROUP BY recipes.RecipeID
WHERE ingredientsNeeded < 4
ORDER BY ingredientsNeeded ASC
您收到错误:
您的SQL语法有错误...请在手册中查找在WHERE附近使用的正确语法...
答案 0 :(得分:1)
您应该使用HAVING
子句对count进行断言:
SELECT
r.RecipeTitle, -- potentially OK to select this, see below
COUNT(r.RecipeID) AS ingredientsNeeded
FROM recipes r
INNER JOIN recipe_ingredients ri
ON ri.RecipeID = r.RecipeID
GROUP BY
r.RecipeID
HAVING
ingredientsNeeded < 4
ORDER BY
ingredientsNeeded;
请注意,您正在按RecipeID
进行汇总,因此从技术上讲,您只能选择或任何汇总。但是,如果RecipeTitle
是RecipeID
表的主键,则允许选择recipes
。