【问题标题】:Count the number of entries in a relational database without aggregate functions?计算没有聚合函数的关系数据库中的条目数?
【发布时间】:2017-09-17 14:49:23
【问题描述】:

所以我需要在不使用聚合函数的情况下计算关系数据库中关联条目的数量。当前数据库代表食谱及其成分。我需要一些类似的东西:

SELECT `RecipeId`,`RecipeTitle`, COUNT(`IngredientId`) AS `IngredientCount` 
FROM `recipes` Natural Join `recipe_ingredients` 
GROUP BY `RecipeID` 
HAVING `IngredientCount` < 5

但不使用 COUNT()。

谢谢。

【问题讨论】:

  • 不数数怎么算? “我在这个纸袋里有一些东西。不用数,告诉我里面有多少”。
  • 出于好奇,您为什么要避免使用聚合函数?它们可能是最有效的方法
  • 只有不带COUNT或者其他聚合函数不能用?
  • 好的!模拟 Row_Number() (按 RecipieID、IngredientID 分区)。然后只拉回 row_number 不大于 5 的配方。模拟示例here。或者也许...blog.sqlauthority.com/2014/03/09/…
  • 循环遍历结果并增加您自己的计数器。但是.. 只需使用聚合函数。

标签: mysql


【解决方案1】:

试试这个:

我不知道 IngredientId 数据类型,如果是文本字段则将 @LastId = 0 更改为 @LastId = ''

SELECT `RecipeId`, `RecipeTitle`, CountIngredient
FROM ( 
      SELECT `RecipeId`, `RecipeTitle`, 
             if(@LastId <> `IngredientId`, @Count := 1, @Count := @Count + 1) CountIngredient, 
             @LastId := `IngredientId`
       FROM 
             (select @Count := 0, @LastId := 0) x,
             (SELECT `RecipeId`, `RecipeTitle` 
              FROM `recipes` Natural Join `recipe_ingredients`
              ORDER BY `RecipeId`) y
    ) z
WHERE z.CountIngredient < 5;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-01
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多