SQL-获取联接表的多个(但不是全部)行的平均值

时间:2018-06-19 15:55:33

标签: mysql sql

我正在尝试使用ROUND(AVG(travisor_review.rating))获得每个行业人士的四舍五入平均评分。但是,这将返回所有评论的平均值,并且仅返回一行,这时每个交易员都应该有一行,并且该交易员的平均值应该只有一行。我的查询如下(希望您可以从中推断出表结构)。

SELECT travisor_tradesperson.name, travisor_catagory.catname, 
  travisor_city.cityname, travisor_company.cname, 
  travisor_company.description, ROUND(AVG(travisor_review.rating))
FROM `travisor_tradesperson`
INNER JOIN travisor_company 
ON travisor_tradesperson.company = travisor_company.id
INNER JOIN travisor_catagory 
ON travisor_tradesperson.catagory = travisor_catagory.id    
INNER JOIN travisor_city 
ON travisor_tradesperson.city = travisor_city.id    
INNER JOIN travisor_review 
ON travisor_review.tradesperson = travisor_tradesperson.id 
WHERE travisor_catagory.catname = '$catagory'
AND travisor_city.cityname = '$city'

1 个答案:

答案 0 :(得分:0)

您需要聚合

SELECT travisor_tradesperson.name, travisor_catagory.catname, 
travisor_city.cityname, travisor_company.cname, 
travisor_company.description, ROUND(AVG(travisor_review.rating))
FROM `travisor_tradesperson`
INNER JOIN travisor_company 
ON travisor_tradesperson.company = travisor_company.id
INNER JOIN travisor_catagory 
ON travisor_tradesperson.catagory = travisor_catagory.id    
INNER JOIN travisor_city 
ON travisor_tradesperson.city = travisor_city.id    
INNER JOIN travisor_review 
ON travisor_review.tradesperson = travisor_tradesperson.id 
WHERE travisor_catagory.catname = '$catagory'
AND travisor_city.cityname = '$city'
group by travisor_tradesperson.name, travisor_catagory.catname, 
travisor_city.cityname, travisor_company.cname, 
travisor_company.description