简体   繁体   English

MySQL:GROUP_CONCAT,AVG和COUNT问题

[英]MySQL: Problem with GROUP_CONCAT, AVG and COUNT

I have a mySQL statement that looks like below. 我有一个如下所示的mySQL语句。 It tries to select all restaurants (1 per row), concat the cuisines for each restaurant (as there may be 1 or more cuisines per restaurant) into a column for each restaurant, and likewise for the average rating and number of ratings. 它尝试选择所有餐厅(每行1个),将每个餐厅的美食(因为每个餐厅可能有1个或更多美食)合并到每个餐厅的列中,并同样对平均评分和评分数进行分类。

I have setup 3 test restaurants. 我已经设置了3家测试餐厅。 Restaurant 1 has 2 cuisine types and 3 ratings. 餐厅1有2种美食类型和3个评分。 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) eg (cuisine1, cuisine1, cuisine1, cuisine2, cuisine2, cuisine2). 问题在于,评分数量返回的是实际值的两倍,而美食则返回为(cuisine1的3倍,然后Cuisine2的3倍),例如(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. GROUP BY将结果分组,而不是单独对表分组。

In your case you want 在你的情况下你想要

  1. The restaurant info. 餐厅信息。
  2. The cuisines. 美食。
  3. 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM