我有两个表,rating
和business
。
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
不幸的是,当我使用聚合函数时,我只有一行?为什么会这样?
答案 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
条款,因为它不需要。你没有过滤任何东西。