简体   繁体   中英

0 rows affected SQL query message

I have this table in my database in eclipse:

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

and I'm trying to display the title of the Recipe containing the fewest ingredients. Here is my query so far:

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

This shows "0 rows affected" so I have no idea what i'm doing wrong. Any help?

You have to JOIN your tables to count number of ingredients for every recipe:

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
)

However, I'm not 100% sure if that's gonna work, because I don't know what database engine you're using.

Either to select the first match, or all matches, depending on what you need - for MSSQL.

First:

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

All:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM