Postgres Database with 3 tables:
recipes(id,recipe_name)
ingredients(id,ingredient_name)
recipes_ingredients(recipe_id,ingredient_id)
Is there any way to write a dynamic sql select that creates a list of the recipes with one column for each ingredient in the ingredients table that has a yes if it is related to the recipe?
Like:
+---------------+-------------------+-------------------+-----+
| recipe_name | ingredient_name 1 | ingredient_name 2 | … |
+---------------+-------------------+-------------------+-----+
| recipe_name 1 | yes | | |
| recipe_name 2 | | yes | |
| recipe_name 3 | yes | | yes |
+---------------+-------------------+-------------------+-----+
Got it to show 0 or 1 ok but is there a simple way to make it dynamic so I don't have to update with every item from the ingredient table?
SELECT
DISTINCT r.recipe_name,
(SELECT COUNT(*) FROM recipes_ingredients WHERE ingredient_id = 1 AND recipe_id = ri.recipe_id) as Tomato,
(SELECT COUNT(*) FROM recipes_ingredients WHERE ingredient_id = 2 AND recipe_id = ri.recipe_id) as Mustard,
(SELECT COUNT(*) FROM recipes_ingredients WHERE ingredient_id = 3 AND recipe_id = ri.recipe_id) as Cucumber,
(SELECT COUNT(*) FROM recipes_ingredients WHERE ingredient_id = 4 AND recipe_id = ri.recipe_id) as Flour
FROM recipes r
INNER JOIN recipes_ingredients ri on ri.recipe_id = r.id
INNER JOIN ingredients i on i.id = ri.ingredient_id
ORDER BY r.recipe_name