创建临时列时出现WHERE子句问题

时间:2020-04-23 02:53:56

标签: sql mariadb

我编写了一个查询,该查询创建了一个新的临时行,其频率显示为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附近使用的正确语法...

1 个答案:

答案 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进行汇总,因此从技术上讲,您只能选择任何汇总。但是,如果RecipeTitleRecipeID表的主键,则允许选择recipes

相关问题