1

我正在尝试编写一个按第一个郊区然后按AVG(rating_table.rating)排序的 mySQL 查询。

这是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

(如您所见,由于avage_rating , #3#2之前)

4

2 回答 2

2

这是一个joinwith 聚合。但是,您需要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
于 2013-09-15T14:38:45.733 回答
0

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

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

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

SELECT .... ORDER BY suburb ASC, AVG(rating_table.rating) DESC;
于 2013-09-15T14:36:46.640 回答