Thursday, January 20, 2022

[FIXED] Sql - How to fetch the single flavor recipes from a intermediate table

Issue

As you can see in the table below, some recipes have 2 or more flavors but some have just 1. I want to take back a table with the flavor_id and the flavor_amount of the single flavor recipes. I managed to do get back some info but i can't take the flavor_amount too.. The closest i got is with this query

SELECT COUNT('flavor_id') as flavors, `recipe_id`, 
MAX(flavor_id) as flavor_id 
FROM `flavor_recipe` 
GROUP BY `recipe_id` 
HAVING flavors = 1;

But still nothing. Any help please? Thank you.

enter image description here


Solution

Gordon's answer reminded me the subqueries. So i thought to give a try and found the solution

SELECT `*`
FROM `flavor_recipe`
WHERE `recipe_id` IN 
   (SELECT `recipe_id` FROM `flavor_recipe` 
   GROUP BY `recipe_id` 
   HAVING COUNT(flavor_id) = 1);

So simple i can't believe i didn't thought of sub queries earlier.. Thanks



Answered By - Evangelos S.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.