0行影响SQL查询消息

时间:2013-04-14 16:30:40

标签: sql sql-server

我在eclipse的数据库中有这个表:

Recipe = (idR, recipeTitle, prepText, cuisineType, mealType)
Ingredient = (idI, ingrDesc)
RecipIngr = (idR*, idI*)

我试图显示含有最少成分的食谱的标题。这是我到目前为止的查询:

  SELECT recipetitle, COUNT(*)
  FROM recipe
  GROUP BY recipetitle
  HAVING COUNT(recipetitle) =
  (SELECT MAX(COUNT(ingrdesc))
  FROM ingredient
  GROUP BY recipetitle);

这显示“0行受影响”所以我不知道我做错了什么。 有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

你必须JOIN你的桌子来计算每个食谱的成分数量:

SELECT
    r.recipeTitle,
    COUNT(*) AS nbOfIng
FROM
    recipe r
JOIN
    RecipIngr ri ON r.idR = ri.idR
GROUP BY
    r.idR, r.recipeTitle
HAVING
    nbOfIng = (
        SELECT
            MAX(COUNT(*))
        FROM
            recipe r2
        JOIN
            RecipIngr ri2 ON r2.idR = ri2.idR
        GROUP BY
            r2.idR
)

但是,我不能100%确定这是否可行,因为我不知道你正在使用什么数据库引擎。

答案 1 :(得分:1)

根据您的需要选择第一场比赛或所有比赛 - 对于MSSQL。

首先:

SELECT TOP 1 RecipeTitle      = R.recipeTitle
       ,IngredientCount = COUNT(*)
FROM   Recipe R
INNER JOIN RecipIngr RI ON R.idR = RI.idR
INNER JOIN Ingredient I ON RI.idI = I.idI
    GROUP BY R.recipeTitle

所有

SELECT dtbl.RecipeTitle
FROM (SELECT RecipeTitle      = R.recipeTitle
       ,IngredientCount = COUNT(*)
           ,rank = rank() OVER (Partition BY R.recipeTitle ORDER BY COUNT(*))
FROM   Recipe R
INNER JOIN RecipIngr RI ON R.idR = RI.idR
INNER JOIN Ingredient I ON RI.idI = I.idI
    GROUP BY R.recipeTitle) dtbl
WHERE dtbl.rank = 1