Hello
I’m trying to learn more about SQL and I have some problems, I don’t know how to combine tables,
I need to use some rows as columns, here is some sample data:
Here are my Tables:
foods |
food_id |
food_name |
1 |
Eggs |
2 |
Strawberries |
3 |
Banana |
4 |
Milk |
nutrition_data
|
food_id |
nutr_no |
nutr_val |
1 |
W1 |
100 |
1 |
P1 |
60% |
1 |
P2 |
30% |
1 |
P3 |
10% |
2 |
W1 |
100 |
2 |
P1 |
0% |
2 |
P2 |
0% |
2 |
P3 |
0% |
3 |
W1 |
100 |
3 |
P1 |
0% |
3 |
P2 |
100% |
3 |
P3 |
0% |
4 |
W2 |
500 |
4 |
P1 |
0% |
4 |
P2 |
0% |
4 |
P3 |
20% |
Definitions |
nutr_no |
units |
NutrDesc |
W1 |
gr |
Weight |
W2 |
ml |
Weight |
P1 |
% |
Protein |
P2 |
% |
Carbs |
P3 |
% |
Fat |
This is the end result I would like to have
RESULT Food Table |
food_id |
Food Name |
Weight |
Protein |
Carbs |
Fat |
1 |
Eggs |
100gr |
60% |
30% |
10% |
2 |
Strawberies |
100gr |
0% |
0% |
0% |
3 |
Banana |
100gr |
0% |
100% |
0 |
4 |
Milk |
500ml |
80% |
0% |
20% |
Use foreign keys. Example: You already have foods table. Add additional field called nutritionData. This field will hold as a value a primary keys of specific column in nutrition_data table. nutrition_data table should have their primary key field, nutr_no, nutr_val fields and definition field. Also duplicate values in nutrition_data should be avoided.
Image of connected table in mysql:
If you want to know summary, for example, of specific users from main table, of specific status. You’ll use foreign keys. Main holds data, status table holds all possible statuses without duplicates.
You’ll find alot docs by googling mysql foreign key. Here is official docs on this subject.