所以我需要在不使用聚合函数的情况下计算关系数据库中相关条目的数量。当前数据库代表食谱及其成分。我需要的是:
SELECT `RecipeId`,`RecipeTitle`, COUNT(`IngredientId`) AS `IngredientCount`
FROM `recipes` Natural Join `recipe_ingredients`
GROUP BY `RecipeID`
HAVING `IngredientCount` < 5
但不使用COUNT()。
谢谢。
答案 0 :(得分:1)
试试这个:
我不知道IngredientId数据类型,如果是文本字段更改@LastId = 0 by @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;