I have 3 Tables: The first Contains Products:
+-----+-------------+---------------+
| ID | NAME | IngredientsID |
+-----+-------------+---------------+
| 01 | Pizza | 01,02,04 |
+-----+-------------+---------------+
| 02 | Spagetti | 01,02 |
+-----+-------------+---------------+
| 03 | Cheesburger | 01,04,02,03 |
+-----+-------------+---------------+
| 04 | Nuggets | 01,04 |
+-----+-------------+---------------+
The second contains Ingredients Details:
+-----+-------------+-------------+--------+
| ID | NAME | Allergens | Frozen |
+-----+-------------+-------------+--------+
| 01 | Flour | 01 | 0 |
+-----+-------------+-------------+--------+
| 02 | Water | | 0 |
+-----+-------------+-------------+--------+
| 03 | Nuts | 03 | 0 |
+-----+-------------+-------------+--------+
| 04 | Fish | 02 | 1 |
+-----+-------------+-------------+--------+
The second contains Allergens details:
+-----+-------------+-------------+
| ID | NAME | Allergens |
+-----+-------------+-------------+
| 01 | Flour | 01 |
+-----+-------------+-------------+
| 02 | Water | |
+-----+-------------+-------------+
| 03 | Nuts | 03 |
+-----+-------------+-------------+
| 04 | Fish | 02 |
+-----+-------------+-------------+
now with a query I need to extract for a given Food_ID
, the list of Ingredients' Names and Allergenes Names:
and I used the following query:
SELECT
ID,
Name,
(
select
GROUP_CONCAT(DISTINCT Name SEPARATOR ',')
from Ingredients
where (select IngredientsID from Products where ID=@Food_ID)
like concat('%',IngredientID,'%')
) IngredientsNames
FROM products
WHERE ID=@Food_ID
(for allergenes Names I used a nested GROUP_CONCAT)
that return for @Food_ID=03
something like:
+-----+-------------+----------------------------+
| ID | Name | IngredientsNames |
+-----+-------------+----------------------------+
| 03 | Cheesburger | Water,Flour,Fish,Nuts |
+-----+-------------+----------------------------+
I'm new with MYSQL, and I tried to use IN
and also FIND_IN_SET
operator but did not succeed: so I used LIKE
:
I think there is a better way to obtain the result, but it works although not perfectly:
in fact, Ingredients has to be indicated according to their quantity in the Dish:
First the most present and so on, while the list of Ingredients give by the query contains ingredients name in random order,
while it should follow the order stated in IngredientsID
in Products
Table:
therefore
Flour,Fish,Water,Nuts
Is there a way to achieve this?
Thanks