سؤال

I have a situation where lets say i'm trying to get the information about some food. Then I need to display all the information plus all the ingredients in that food.

With my query, i'm getting all the information in an array but only the first ingredient...

   myFoodsArr = 
        [0]
          foodDescription = "the description text will be here"
          ratingAverage = 0
          foodId = 4
          ingredient = 1
          ingAmount = 2
          foodName = "Awesome Food name"
          typeOfFood = 6
          votes = 0

I would like to get something back like this...

        myFoodsArr = 
            [0]
              foodDescription = "the description text will be here"
              ratingAverage = 0
              foodId = 4
              ingArr = {ingredient: 1, ingAmount: 4}, {ingredient: 3, ingAmount: 2}, {ingredient: 5, ingAmount: 1}
              foodName = "Awesome Food name"
              typeOfFood = 6
              votes = 0

This is the query im working with right now. How can I adjust this to return the food ID 4 and then also get ALL the ingredients for that food? All while at the same time doing other things like getting the average rating of that food?

Thanks!

   SELECT a.foodId, a.foodName, a.foodDescription, a.typeOfFood, c.ingredient, c.ingAmount, AVG(b.foodRating) AS ratingAverage, COUNT(b.foodId) as tvotes 
FROM `foods` a 
LEFT JOIN `foods_ratings` b 
   ON a.foodId = b.foodId 
LEFT JOIN `foods_ing` c 
   ON a.foodId=c.foodId 
WHERE a.foodId=4

EDIT:

Catcall introduced this concept of "sub queries" I never heard of, so I'm trying to make that work to see if i can do this in 1 query easily. But i just keep getting a return false. This is what I was trying with no luck..

//I changed some of the column names to help them be more distinct in this example

SELECT a.foodId, a.foodName, a.foodDescription, a.typeOfFood, AVG(b.foodRating) AS ratingAverage, COUNT(b.foodId) as tvotes 
FROM foods a 
LEFT JOIN foods_ratings b ON a.foodId = b.foodId 
LEFT JOIN (SELECT fId, ingredientId, ingAmount 
                 FROM foods_ing 
                 WHERE fId = 4 
                 GROUP BY fId) c ON a.foodId = c.fId 
           WHERE a.foodId = 4";

EDIT 1 more thing related to ROLANDS GROUP_CONCAT/JSON Idea as a solution 4 this

I'm trying to make sure the JSON string im sending back to my Flash project is ready to be properly parsed Invalid JSON parse input. keeps popping up..

so im thinking i need to properly have all the double quotes in the right places.

But in my MySQL query string, im trying to escape the double quotes, but then it makes my mySQL vars not work, for example...

If i do this..

GROUP_CONCAT('{\"ingredient\":', \"c.ingredient\", ',\"ingAmount\":', \"c.ingAmount\", '}')`

I get this...

{"ingredient":c.ingredient,"ingAmount":c.ingAmount},{"ingredient":c.ingredient,"ingAmount":c.ingAmount},{"ingredient":c.ingredient,"ingAmount":c.ingAmount}

How can i use all the double quotes to make the JSON properly formed without breaking the mysql?

هل كانت مفيدة؟

المحلول

This should do the trick:

SELECT    food_ingredients.foodId
,         food_ingredients.foodName
,         food_ingredients.foodDescription
,         food_ingredients.typeOfFood
,         food_ingredients.ingredients
,         AVG(food_ratings.food_rating) food_rating
,         COUNT(food_ratings.foodId)    number_of_votes 
FROM      (
           SELECT    a.foodId
           ,         a.foodName
           ,         a.foodDescription
           ,         a.typeOfFood
           ,         GROUP_CONCAT(
                         '{ingredient:', c.ingredient,
                     ,   ',ingAmount:', c.ingAmount, '}'
                     ) ingredients
           FROM      foods a 
           LEFT JOIN foods_ing c 
           ON        a.foodsId = c.foodsId 
           WHERE     a.foodsId=4
           GROUP BY  a.foodId
          ) food_ingredients
LEFT JOIN food_ratings
ON        food_ingredients.foodId = food_ratings.foodId
GROUP BY  food_ingredients.foodId 

Note that the type of query you want to do is not trivial in any SQL-based database.

The main problem is that you have one master (food) with two details (ingredients and ratings). Because those details are not related to each other (other than to the master) they form a cartesian product with each other (bound only by their relationship to the master).

The query above solves that by doing it in 2 steps: first, join to the first detail (ingredients) and aggregate the detail (using group_concat to make one single row of all related ingredient rows), then join that result to the second detail (ratings) and aggregate again.

In the example above, the ingredients are returned in a structured string, exactly like it appeared in your example. If you want to access the data inside PHP, you might consider adding a bit more syntax to make it a valid JSON string so you can decode it into an array using the php function json_decode(): http://www.php.net/manual/en/function.json-decode.php

To do that, simply change the line to:

CONCAT(
    '['
,   GROUP_CONCAT(
        '{"ingredient":', c.ingredient
    ,   ',"ingAmount":', c.ingAmount, '}'
    )
,   ']'
)

(this assumes ingredient and ingAmount are numeric; if they are strings, you should double quote them, and escape any double quotes that appear within the string values)

The concatenation of ingredients with GROUP_CONCAT can lead to problems if you keep a default setting for the group_concat_max_len server variable. A trivial way to mitigate that problem is to set it to the maximum theoretical size of any result:

SET group_concat_max_len = @@max_allowed_packet;

You can either execute this once after you open the connection to mysql, and it will then be in effect for the duration of that session. Alternatively, if you have the super privilege, you can change the value across the board for the entire MySQL instance:

SET GLOBAL group_concat_max_len = @@max_allowed_packet;

You can also add a line to your my.cnf or my.ini to set group_concat_max_lenght to some arbitrary large enough static value. See http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_group_concat_max_len

نصائح أخرى

One obvious solution is to actually perform two queries:

1) get the food

SELECT a.foodId, a.foodName, a.foodDescription, a.typeOfFood
FROM `foods` a
WHERE a.foodsId=4

2) get all of its ingredients

SELECT c.ingredient, c.ingAmount
FROM `foods_ing` c
WHERE c.foodsId=4

This approach has the advantage that you don't duplicate data from the "foods" table into the result. The disadvantage is that you have to perform two queries. Actually you have to perform one extra query for each "food", so if you want to have a listing of foods with all their ingredients, you would have to do a query for each of the food record.

Other solutions usually have many disadvantages, one of them is using GROUP_CONCAT function, but it has a tough limit on the length of the returned string.

When you compare MySQL's aggregate functions and GROUP BY behavior to SQL standards, you have to conclude that they're simply broken. You can do what you want in a single query, but instead of joining directly to the table of ratings, you need to join on a query that returns the results of the aggregate functions. Something along these lines should work.

select a.foodId, a.foodName, a.foodDescription, a.typeOfFood, 
       c.ingredient, c.ingAmount,
       b.numRatings, b.avgRating
from foods a
left join (select foodId, count(foodId) numRatings, avg(foodRating) avgRating
           from foods_ratings
           group by foodId) b on a.foodId = b.foodId
left join foods_ing c on a.foodId = c.foodId
order by a.foodId
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top