简体   繁体   中英

Return all items that are only used once in table

List the names of all ingredients that are used in only one recipe (1 column, 46 rows)

Logically the way I understand this query is that I need count the IngredientID 's in the Recipe_Ingredients column to find the instances where an IngredientID appears only once. But my query isn't returning any results.

I've tried substituting count(Ingredients.IngredientID) with count(*) and sum() . But both returned no results as well.

select Ingredients.IngredientName
from Ingredients
join Recipe_Ingredients on Ingredients.IngredientID = Recipe_Ingredients.RecipeID
group by Ingredients.IngredientName
having count(Ingredients.IngredientID) = 1;

DB Structure SQL File

DB Data SQL File

在此处输入图片说明

You're not joining on the correct column; it should be

Ingredients.IngredientID = Recipe_Ingredients.IngredientID

Making this change gives the correct result of 46 rows: demo

Note that preparing a dbfiddle as I did makes it a lot easier for others to answer your question.

Get the ingredients that are in the table of Recipe_Ingredients only once.

select * from Ingredients a where IngredientID in
(
select IngredientID
from Recipe_Ingredients 
group by IngredientID
having count(*) = 1
)
select Ingredients.IngredientName
from Ingredients
join Recipe_Ingredients on Ingredients.IngredientID = Recipe_Ingredients.IngredientID
group by Ingredients.IngredientName
having count(Ingredients.IngredientID) = 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