MySQL: Problem with GROUP_CONCAT, AVG and COUNT
I have a mySQL statement that looks like below. It tries to select all restaurants (1 per row), concat the cuisines for each restaurant (as there may be开发者_StackOverflow社区 1 or more cuisines per restaurant) into a column for each restaurant, and likewise for the average rating and number of ratings.
I have setup 3 test restaurants. Restaurant 1 has 2 cuisine types and 3 ratings. The problem is that the number of ratings returns double the actual value and the cuisines return as (cuisine1 3 times then cuisine2 3 times) e.g. (cuisine1, cuisine1, cuisine1, cuisine2, cuisine2, cuisine2). Do you know what could be causing this? Thanks for any help.
SELECT
r.*,
GROUP_CONCAT(c.cuisine SEPARATOR ', ') cuisine,
ROUND(AVG(re.avg_rating),1) rating,
COUNT(re.restaurant_id) num_ratings
FROM eat_eat_restaurants r
JOIN eat_eat_restaurant_cuisines_lookup rc ON (r.restaurant_id=rc.restaurant_id)
JOIN eat_eat_cuisines c ON (rc.cuisine_id=c.cuisine_id)
LEFT JOIN eat_eat_reviews re ON (r.restaurant_id=re.restaurant_id)
WHERE r.published=1
GROUP BY r.restaurant_id
GROUP BY
groups the results, not the tables individually.
In your case you want
- The restaurant info.
- The cuisines.
- The ratings.
Since the "cuisines" and the "ratings" are not dependent with each other, one of them need to be grouped by itself:
SELECT
r.*,
GROUP_CONCAT(c.cuisine SEPARATOR ', ') cuisine,
reg.rating,
reg.num_ratings
FROM eat_eat_restaurants r
JOIN eat_eat_restaurant_cuisines_lookup rc ON r.restaurant_id=rc.restaurant_id
JOIN eat_eat_cuisines c ON rc.cuisine_id=c.cuisine_id
LEFT JOIN (
SELECT re.restaurant_id,
ROUND(AVG(re.avg_rating),1) rating,
COUNT(re.restaurant_id) num_ratings
FROM eat_eat_reviews re
GROUP BY re.restaurant_id
) reg ON r.restaurant_id=reg.restaurant_id
WHERE r.published=1
GROUP BY r.restaurant_id
精彩评论