MySQL从一个表返回不同的帐户,从另一个表返回平均值,所有这些都基于另一个表中的服务区域

时间:2015-10-01 17:56:33

标签: mysql join

正如标题所述,我正在尝试返回一个查询,该查询从帐户表中获取帐户详细信息,从评论表中获取该帐户的平均评级,并将行限制为与该帐户关联的服务位置。

以下是简化表:

账户

+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
|  1 | John       | Smith     |
|  2 | Bob        | Doe       |
|  3 | Alice      | McLovin   |
|  4 | Bruce      | Wayne     |
+----+------------+-----------+

评论

+----+-------------+-----+--------+
| id | acccount_id | ... | rating |
+----+-------------+-----+--------+
|  1 |           1 | ... |      9 |
|  2 |           1 | ... |     10 |
|  3 |           2 | ... |      7 |
|  4 |           1 | ... |      2 |
|  5 |           4 | ... |      6 |
+----+-------------+-----+--------+

service_area

+----+-------------+---------+
| id | acccount_id | city_id |
+----+-------------+---------+
|  1 |           1 |    1140 |
|  2 |           1 |    1001 |
|  3 |           2 |    1140 |
|  4 |           1 |    1086 |
|  5 |           4 |    1001 |
+----+-------------+---------+

例如,用户可以请求查看具有city_id 1140的服务区域的所有帐户。然后,查询应该返回指定服务区域内的每个帐户的first_name,last_name和平均评级。请注意,帐户可以有多个服务区域(请参阅service_area表)。

提前致谢!

更新:

以下QUERY做了伎俩!我需要为评论表提供LEFT JOIN!

SELECT a.first_name, a.last_name, AVG(r.rating) avg_rating
FROM accounts a
JOIN service_area sa
ON a.id = sa.account_id AND sa.city_id = 1140
LEFT JOIN reviews r 
ON a.id = r.account_id
GROUP BY a.id

1 个答案:

答案 0 :(得分:0)

您可以使用

分组加入和简单聚合
SELECT a.*,
AVG(r.rating) avg_rating
FROM accounts a
JOIN reviews r ON a.id = r.acccount_id
JOIN service_area s ON a.id = s.acccount_id
WHERE s.city_id = 1140
GROUP BY a.id

结果集将类似于

    id  first_name  last_name  avg_rating  
------  ----------  ---------  ------------
     1  John        Smith            7.0000
     2  Bob         Doe              7.0000

在没有评论时使用LEFT加入

SELECT a.*,
COALESCE(AVG(r.rating),0) avg_rating
FROM accounts a
LEFT JOIN reviews r ON a.id = r.acccount_id
JOIN service_area s ON a.id = s.acccount_id
WHERE s.city_id = 1140
GROUP BY a.id

DEMO