I have a problem with SQL Query. I tried many hours and searched the Internet, but I can not find what I need.
I have 2 tables that are linked through an identifier as a primary key and a foreign key. The values inside the second table have a specific category. Each value in the second table refers only to a separate category. I need to sort this inside a query in new categories. Now multiple values can have the same category. The desired result is a list of these new categories with their respective counter, including 0.
I tried different associations with subtitles, etc., but I did not get the desired result.
Unfortunately, I cannot show you the excact / query tables, so I tried to replicate the problem (I hope this is clear)
My tables:
meals:
| id | name | food_id |
+----+------+---------+
| 01 | Pete | 001 |
| 02 | Anna | 002 |
| 03 | Jim | 003 |
| 04 | John | 002 |
| 05 | Lucy | 003 |
food:
| id | name |
+-----+--------+
| 001 | Apple |
| 002 | Banana |
| 003 | Carrot |
| 004 | Steak |
My request:
SELECT food.foodtype AS foodtype,
COUNT(food.foodtype) AS amount
FROM (
SELECT food.id AS id
CASE WHEN food.name = 'Apple' THEN 'Fruit',
WHEN food.name = 'Banana' THEN 'Fruit',
WHEN food.name = 'Carrot' THEN 'Vegetable',
WHEN food.name = 'Steak' THEN 'Meat',
END AS foodtype
FROM food
) AS food
INNER JOIN meals
ON meals.food_id = food.id
GROUP BY food.foodtype
The result of this query is a table with all types of food used, but I also need unused food types displayed as 0.
| foodtype | amount |
+-----------+--------+
| Fruit | 3 |
| Vegetable | 2 |
As a result, I need:
| foodtype | amount |
+-----------+--------+
| Fruit | 3 |
| Vegetable | 2 |
| Steak | 0 |
Another idea that I had, but still not needed:
SELECT CASE WHEN food.name = 'Apple' THEN 'Fruit',
WHEN food.name = 'Banana' THEN 'Fruit',
WHEN food.name = 'Carrot' THEN 'Vegetable',
WHEN food.name = 'Steak' THEN 'Meat',
END AS foodtype
COUNT(meals.id) AS amount
FROM meals
RIGHT JOIN food
ON food.id = meals.food_id
GROUP BY food.name
My result:
| foodtype | amount |
+-----------+--------+
| Fruit | 1 |
| Fruit | 2 |
| Vegetable | 2 |
| Meat | 0 |
I hope this is understandable, what I need, and someone can help me with this problem.