I am stuck on a nested database query. Can I get some help?
My simple table looks like this:
food_table:
+----+----------+-------------------------------+
| ID | NAME | nutrientName | NutrientAmount
+----+----------+---------------+---------------+
food1 calcium 200
food1 magnesium 300
food1 phosphorus 400
food2 calcium 220
food2 magnesium 320
food2 phosphorus 430
food3 calcium 230
.............
I used this to get top 15 nutrition amount:
select NAME from food_table
where nutrientName in ('calcium','magnesium')
group by NAME
order by sum(nutrient_amount) desc
limit 15;
Currently, I only have NAME. But, I want to get the all nutrition of the food and with the same order. If I do another select, the order will be lost. Is there a way to get the food records and with the same order?
Edit: I've created a fiddle: