按平均排序(评级)

时间:2013-09-15 14:34:44

标签: mysql

我正在尝试编写一个mySQL查询,首先按郊区进行排序,然后 AVG(rating_table.rating)

以下是 street_table

id       street_name       suburb

0        streetone         subone
1        streettwo         subthree
2        streetthree       subthree
3        streetfour        subtwo

这是 rating_table

street_id    rating

1            1
2            1
3            4
2            2
1            3

这就是我要找的结果:

id      suburb         avarage_rating

0       subone         (no rating)
1       subtwo         1 + 3 / 2 = 2
3       subthree       4 / 1 = 4 (Just one vote..)
2       subthree       2 + 1 / 2 = 1.5

(正如您所见,#3 #2 之前,因为 avarage_rating

2 个答案:

答案 0 :(得分:2)

这是一个带有聚合的join。但是,您需要left join以确保所有行都没有评级:

select s.id as street_id, s.suburb, avg(r.rating) as rating
from street_table s left join
     rating_table r
     on s.id = r.street_id
group by s.id, s.suburb
order by s.suburb, avg(r.rating) desc

答案 1 :(得分:0)

您可以将ORDER BY组合使用多个列,例如:

SELECT .... ORDER BY suburb, AVG(rating_table.rating);

您也可以定义特定于项目的订单

SELECT .... ORDER BY suburb ASC, AVG(rating_table.rating) DESC;