recipe_category
cid | category
1 | desserts
2 | cakes
3 | biscuits
recipe_name
id | recipe_name | cid | iid
1 | black forest cake | 1,2 | 1,2,3,4
2 | angel cake | 2 | 1,2,4
3 | melting moments | 3 | 2,5
4 | croquembouche | 1,3 | 1,5
ingredients
iid | ingredient_name
1 | self-raising flour
2 | milk
3 | chocolate
4 | baking powder
5 | plain flour
I am able to query the DB using cid to pull certain recipes, ie. desserts:
SELECT * FROM recipe_name WHERE cid='1'
But then how do I create a list of ingredients like the below where ingredients are listed with <br>?
Black Forest Cake:
Self-Raising Flour
Milk
Chocolate
Baking Powder
I’m new to this, so please forgive any stupid questions!
Storing multivalued attributes in a single comma separated field is almost always a bad idea. It makes everything very difficult to query.
Instead, you may want to consider refactoring your schema, using two new intersection tables.
These two tables remain as they are (just changed name of
recipe_categorytocategoriesin order not to clash with the intersection table):Modify the
recipe_nametable as follows, removing thecidandiidfields:Then you can define your multivalued relationships using the following two intersection tables:
Now let’s populate these tables with your example data:
To define the relationships between the recipes and their ingredients and categories, you would need to fill up the intersection tables as follows:
Finally, building your query will be as easy as this:
Result:
You may then want to format that result set (adding the
<br>s) in your application code instead of in SQL.However if you really wish to do that in SQL, then MySQL supports the handy
GROUP_CONCAT()function, which can be used as follows:Result:
Dump that into HTML, and you’re good to go!