如何离开聚合函数的连接?

时间:2014-10-08 14:35:36

标签: mysql sql

我有两个表,ratingbusiness

rating表:

bussId    userId     rating
----------------------------
  5          454       3
  8          684       5
  8          102       2

business表:

bussId     businessName
-----------------------
   5           name1
   8           name2

我想通过此查询获得bussName及其评分:

SELECT business.businessName,
 COUNT(rating.rating) as ratingCount,
 SUM(rating.rating)as ratingSum
FROM business 
LEFT JOIN (business.bussId = rating.bussId) 
WHERE 1

不幸的是,当我使用聚合函数时,我只有一行?为什么会这样?

1 个答案:

答案 0 :(得分:1)

嗯,你有一些语法问题。 FROM的{​​{1}}子句缺少LEFT JOIN表的连接。您缺少JOIN的rating子句。由于您正在汇总数据,因此您错过了ON。查询应为:

GROUP BY

SQL Fiddle with Demo。如果您没有将GROUP BY与您的聚合函数一起使用,那么您将无法返回每个SELECT business.businessName, COUNT(rating.rating) as ratingCount, SUM(rating.rating) as ratingSum FROM business LEFT JOIN rating ON business.bussId = rating.bussId GROUP BY business.businessName; 的数据,MySQL将选择一个值来返回。

注意:我删除了businessName条款,因为它不需要。你没有过滤任何东西。